473,793 Members | 2,742 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Alternatives to #define?

What other c++ constructs can I use instead of #define for executing a
couple of functions?
Example:

#define DO_STUFF doThis(); doThat();

I'd guess that I can either use a template function, an inlined function or
an inlined static method.

//1
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}

//2
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}

//3
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}

I *believe* that the template version always is inlined, and that the other
2 versions is probably inlined.
Are theese approaches correct?
Which should be preferred?
Are there any other better way?

/Carl
Jul 22 '05 #1
14 4463

"Carl Ribbegaardh" <ca************ *********@hotma il.com> wrote in message
news:2k******** ****@uni-berlin.de...
What other c++ constructs can I use instead of #define for executing a
couple of functions?
Example:

#define DO_STUFF doThis(); doThat();

I'd guess that I can either use a template function, an inlined function or an inlined static method.

//1
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}

//2
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}

//3
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}

I *believe* that the template version always is inlined, and that the other 2 versions is probably inlined.
No that is not true. I guess you are thinking of the exception that
templates have from the normal one definition rules for functions and
classes. But that's an entirely seperate issue.
Are theese approaches correct?
They are all correct.
Which should be preferred?
The second
Are there any other better way?


What's wrong with the second method? Why is it even an issue?

john
Jul 22 '05 #2

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2k******** ****@uni-berlin.de...

"Carl Ribbegaardh" <ca************ *********@hotma il.com> wrote in message
news:2k******** ****@uni-berlin.de...
What other c++ constructs can I use instead of #define for executing a
couple of functions?
Example:

#define DO_STUFF doThis(); doThat();

I'd guess that I can either use a template function, an inlined function

or
an inlined static method.

//1
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}

//2
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}

//3
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}

I *believe* that the template version always is inlined, and that the

other
2 versions is probably inlined.


No that is not true. I guess you are thinking of the exception that
templates have from the normal one definition rules for functions and
classes. But that's an entirely seperate issue.
Are theese approaches correct?


They are all correct.
Which should be preferred?


The second
Are there any other better way?


What's wrong with the second method? Why is it even an issue?


The issue is that I dont *know*.
I'm currently just guessing/believing. :)

So the 1st version isn't inlined? Why I thought it would be, is that I've
read lines like "templates are inlined by definition" but I might have
interpreted/read/remembered it wrong. Any elaboration on why or why not
would be much appreciated.

Thanks! :)
Jul 22 '05 #3

"Carl Ribbegaardh" <ca************ *************** **************@ hotmail.com>
wrote in message news:2k******** ****@uni-berlin.de...

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2k******** ****@uni-berlin.de...

"Carl Ribbegaardh" <ca************ *********@hotma il.com> wrote in message news:2k******** ****@uni-berlin.de...
What other c++ constructs can I use instead of #define for executing a
couple of functions?
Example:

#define DO_STUFF doThis(); doThat();

I'd guess that I can either use a template function, an inlined
function or
an inlined static method.

//1
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}

//2
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}

//3
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}

I *believe* that the template version always is inlined, and that the other
2 versions is probably inlined.


No that is not true. I guess you are thinking of the exception that
templates have from the normal one definition rules for functions and
classes. But that's an entirely seperate issue.
Are theese approaches correct?


They are all correct.
Which should be preferred?


The second
Are there any other better way?


What's wrong with the second method? Why is it even an issue?


The issue is that I dont *know*.
I'm currently just guessing/believing. :)


Well method two is using one function to call two others. It's perfectly
common programming to solve a common problem. The other methods introduce
extra language features to create a more complex solution to a simple
problem.
So the 1st version isn't inlined? Why I thought it would be, is that I've
read lines like "templates are inlined by definition" but I might have
interpreted/read/remembered it wrong. Any elaboration on why or why not
would be much appreciated.


If you read that it was wrong. As I said I think you might have read that
template functions usually go in header files which makes them a little like
inline functions (which also usually go in header files), but this is for
technical issues to do with how templates are compiled. It has nothing to do
with whether the template function call itself is inlined.

john
Jul 22 '05 #4
Carl Ribbegaardh wrote:
What other c++ constructs can I use instead of #define for executing a
couple of functions?
Example:

#define DO_STUFF doThis(); doThat();

I'd guess that I can either use a template function, an inlined
function or an inlined static method.

//1
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}
What's that template good for? Actually, I don't think this is valid,
since it doesn't have any template parameters.
//2
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}

//3
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}
That's incorrect. You cannot make a static member function const, as
that wouldn't make sense. Making a member function const means that it
can be called on const objects, but a static member function isn't
called on any object at all.
I *believe* that the template version always is inlined, and that the
other 2 versions is probably inlined.


No. The template might be inlined or it might not, just like any other
function.

Jul 22 '05 #5
"Carl Ribbegaardh" <ca************ *********@hotma il.com> wrote:
#define DO_STUFF doThis(); doThat();
I actually like that. Simple, direct, ALWAYS inlined.
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}
I tried compiling that, got "Error: non-template
used as template."
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}
That works, and most C++ purists would recommend it,
but I think it sucks. Too complicated. KISS.
Use the macro instead.
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}


"error: static member function `static void MyUtils::doStuf f()'
cannot have `const' method qualifier"

Why stir up trouble with complicated stuff when trying to
solve a simple problem? Usually the simpliest workable
solution is the best. Sometimes a macro is the thing that fits
that bill.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant




----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 22 '05 #6
"Robbie Hatley" <lonewolfintj at pacbell dot net> wrote in message
news:40******** @127.0.0.1...
"Carl Ribbegaardh" <ca************ *********@hotma il.com> wrote:
#define DO_STUFF doThis(); doThat();
I actually like that. Simple, direct, ALWAYS inlined.
namespace MyUtils
{
template<>
void doStuff()
{
doThis();
doThat();
}
}


I tried compiling that, got "Error: non-template
used as template."


Yes, I just wrote it in the news reader. Think of it as pseudo code ;)
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}
That works, and most C++ purists would recommend it,
but I think it sucks. Too complicated. KISS.
Use the macro instead.
class MyUtils
{
public:
static inline void doStuff() const
{
doThis();
doThat();
}
}


"error: static member function `static void MyUtils::doStuf f()'
cannot have `const' method qualifier"


Yes, the const should probably go away. It's also just invented on the fly
to show roughly how I thought. Pseudo code ;)
Why stir up trouble with complicated stuff when trying to
solve a simple problem? Usually the simpliest workable
solution is the best. Sometimes a macro is the thing that fits
that bill.

But macros can be difficult to follow too. This example is very simplistic,
but for example logging macros and testing macros can be difficult to read
and maintain. But I do like how the compiler has an opportunity to remove
large parts of the code by switching a compiler flag.

I'm just interested in learning different techniques of performing the same
task, just to improve my toolbox :)

Thanks!
/Carl

--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant




----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption

=---
Jul 22 '05 #7

just use this.
namespace MyUtils
{
inline void doStuff()
{
doThis();
doThat();
}
}
That works, and most C++ purists would recommend it,
but I think it sucks. Too complicated. KISS.
Use the macro instead.


this is probably the most bizarre thing i've read in a while. it works,
huh?:

for (int i = 0; i < 10; ++i)
STUFF

vs.

for (int i = 0; i < 10; ++i)
doStuff();

"kiss" that.
But macros can be difficult to follow too. This example is very simplistic,
but for example logging macros and testing macros can be difficult to read
and maintain. But I do like how the compiler has an opportunity to remove
large parts of the code by switching a compiler flag.
inline functions were largely created for the explicit purpose of
eliminating macros.

#define DO_STUFF doThis(); doThat();

and

inline void doStuff()
{
doThis();
doThat();
}

should produce *exactly* the same output instructions under most
circumstances (of course, the compiler is free to ignore the inline
suggestion, and most do under certain circumstances). that's what they
were created for.

you want the power to be able to effectively turn that function off in
certain compile-time conditions (eg, removing it in a release build)? no
problem:

inline void doStuff()
{
#ifdef DEBUG
doThis();
doThat();
#endif
}

that will be a no-op on any compiler worth its salt if DEBUG is not
defined. need a parameter? piece of cake:

inline void doStuff(int param)
{
doThis(param);
doThat(param);
}

just try that with macros:

#define STUFF(x) doThis(x); doThat(x);
STUFF(++i); // uh oh!

also, what if you need a dummy/default variable for the call?

inline void doStuff()
{
int temp;
doThis(&temp);
doThat(temp);
}

works with the macro? well...

#define STUFF int temp; doThis(&temp); doThat(temp);

void foo()
{
STUFF
// some code
STUFF // bang!
}

incidently:

class MyUtils
{
public:
static void doStuff() // implicit inline
{
doThis();
doThat();
}
};

would work, and may be valid in certain instances. i was involved in a
lengthy debate about the merit of such a design pattern a while back. no
real conclusion was reached, but i believe that 99% of the time this
method is unnecessary and convoluted, and it's even occasionally
dangerous. however, you're the programmer, do what you will.
I'm just interested in learning different techniques of performing the same
task, just to improve my toolbox :)


bien sur. macros do have their place. and all the problems i presented
above with the macros *could* be fixed. but seriously, how can you think
inline funcitons are "too complicated" when you have to take so much
care with them? use them only when direct text substitution is desired.
_never_ use the preprocessor in place of c++ language constructs.

as far as i can think right now, inline functions (and inlined static
public class members of course) are about the only way to do what you
want. macros *can* do it, if you're careful, but are most definitely not
the best way to do it.

of course, regular non-inlined functions could do the same thing,
although possibly with additional overhead. i say this because often in
the rush to optimize, rationality goes out the window. after all, you're
already paying for the overhead *twice* with doThis() and doThat(). if
either function takes any practical length of time, the overhead in
calling doStuff() is pretty much marginalized.

also, an optimizing compiler would probably realize that setting up the
stack frame in doStuff is unnecessary, so the entire cost of the
function (not counting doThis() and doThat(), of course) comes down to
two jump instructions. that's two jump instructions, likely a call and a
ret on x86's, and possibly even less in special cases. is that too
expensive?

and that's assuming the compiler doesn't inline it anyway. stay away
from macro crap. trust your compiler... but use your profiler.

mark
Jul 22 '05 #8
* Rolf Magnus:
Alf P. Steinbach wrote:
* Rolf Magnus:
Alf P. Steinbach wrote:

> * Rolf Magnus:
>>
>> #define DO_STUFF do { doThis(); doThat(); } while(false)
>
> Unfortunately that may cause a warning with too "helpful" compilers
> such as Visual C++.
>
> Try instead
>
> #define DO_STUFF for(;;){ doThis; doThat(); break; }

Hmm, what would you gain with that for loop?


See above.


No, I mean what you gain compared to just:

#define DO_STUFF() { doThis(); doThat(); }


Uhm, see my reply to Rob Williscroft. I was wrong. And the extreme
irony is that I've always used do-while for such things precisely
because a simple block won't do wrt. semicolon syntax, and done my best
to teach that technique to others (since you can read Norwegian as well
as C++ code I can offer an example of such teaching, namely the XASSERT
macro in <url: http://home.no.net/dubjai/03/index.html#cppu til>,
presumably some Googling on newsgroup posting would give more examples).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #9
"Mark A. Gibbs" <x_*********@ro gesr.com_x> wrote in message
news:rq******** ******@news04.b loor.is.net.cab le.rogers.com.. .

Carl Ribbegaardh wrote:
Very enlightening post. I think that you might have mixed up who thought
what about macros and inline functions, but it really doesn't matter.
This was exactly the info about alternatives to macros I was looking
for. :)
thank you, and don't worry, i was aware i was replying two steps removed
when i was harping about the dangers of macros. sorry if i gave the
impression otherwise.

mark


One more question on the subject:

Why is (for example) SUCCEEDED and FAILED (in winerror.h) implemented as
macros?
...and other stuff that's common like SAFE_DELETE and so on...

Is it just done by habit, or are there any other reason for not using inline
functions?

:)
/Carl
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
2087
by: CYBER | last post by:
Hello Is there any other way under python to create blocks ?? instead of def sth(x): return x
9
1688
by: Simon Elliott | last post by:
If I have a base class and several possible derived classes, and I have a pointer to the base class, what's the best way of determining whether the pointer is pointing to a base class or to a derived class? The classes have virtual functions, so I could use a dynamic_cast. Is there much overhead associated with this? Alternatively I could have an instance variable in the base class which derived classes are required to set, or a...
2
1752
by: Michael | last post by:
Ok Guys, on the same thread I'm writing a Game engine, which performs collision detection. I want to sepate the collision boundings libaray from the main game engine and load it as a library. If simplified this example but it illustrates the point.... :-) So i declare an abstract base class ( & function ): ///////////////////////////////////////////////////
0
1481
by: Imre | last post by:
I'm planning to create a macro-based property system (reflection, automatic serializing for properties, that kind of stuff). The system would involve writing some PROPERTY(propName) macros between a BEGIN_CLASS(ThisClass) and an END_CLASS() macro. The PROPERTY macros should somehow know ThisClass, and that's where it start to get tricky. A #define ThisClass would of course help, but I'd rather make it part of the BEGIN_CLASS macro, and...
43
5029
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own libraries. I'm not sure if that's a good thing or not. AFAIK, most of Qt is compatable with the Standard Library. That is, QLT can interoperate with STL, and you can convert back and forth between std::string and Qt::QString, etc. Are there any...
1
1299
by: Doug | last post by:
Looking for opinions/suggestions: Suppose I have a "region" of an aspx page I want to hide or show based on whatever runtime conditions. Additionally, the entire region is defined by an HTML <TABLE>. There is nothing else in the region beyond whatever is contained in the <TABLE>. I see at least two options for showing/hiding this region. 1. Wrap the table in an <ASP:Panel> and set the panel's Visible property to
6
2159
by: greek_bill | last post by:
Hi, I'm interested in developing an application that needs to run on more than one operating system. Naturally, a lot of the code will be shared between the various OSs, with OS specific functionality being kept separate. I've been going over the various approaches I could follow in order to implement the OS-specific functionality. The requirements I have are as follows :
4
1290
by: sunderjs | last post by:
Hi, This is from a typical telecom software implementation. I have three subsystems (x, y, z) which exchange data amongst them. The arrangement is such that x talks to y over interface xy. y subsystem them talks to z over yz interface. In a typical scenario, y would receive a set of parameters from x (over xy). Some of these are meant for z subsys as well. So y needs to send these plus some more parameters to z. The implementation...
0
2534
by: howa | last post by:
Hello Besides YUI grid / builder (http://developer.yahoo.com/yui/grids/ builder/), are there any alternatives such that it provides a very flexible way to define site grid yet conform to the web standard? I just want to compare them if you got any good suggestions. Thanks.
0
9671
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6777
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.