Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
What would be the best replacement for #define when generating code?

We have a series of macros (#define) that will be used to "generate" code

for (a simplified) example

C++
#define SOME_CODE( name, defaultValue ) \
  if ( m_##name == defaultValue ) \
  { \
  // do something \
  }

and will be called

C++
SOME_CODE(radius, 33)
SOME_CODE(length, 42)
SOME_CODE(width, 69)



Our actual SOME_CODE define is relatively complex (multiple parameters, creates loops...)

Is there a better way in C++ to do that?
Posted
Comments
Richard MacCutchan 9-Jun-15 11:17am    
If the parameters in each call are the same type, then it would be better to write a single function. I find that macros in general are a bad idea in C/C++.
Albert Holguin 9-Jun-15 22:56pm    
Why not just use a class? ...if you need the types to be generic, use a template. The code will be easier to follow and maintain.
Philippe Mori 12-Jun-15 12:26pm    
With so little code, it is impossible to give specific advices. Maybe it would make sense to replace the member by a class that contains the current and default value...

The only other technique I am aware of, using just the C++ compiler, is template metaprogramming (see the Wikipedia page[^]).
Of course, you might also use an external tool to produce C++ source code
(e.g. generating C++ code from a Lua table).
 
Share this answer
 
The question isn't so much what you can use to duplicate that technique of mashing code symbols together, but finding out why you thought you'd need it in the first place, and then decide on an appropriate, modern way to solve it.

That said, since the example seems to be about a 'simplified' set functionality, let me point you to the __declspec(property) statement that VisualStudio provides. I'm not a big fan, in part because it's VS-specific, but maybe it helps you achieve something similar: https://msdn.microsoft.com/en-us/library/yhfk0thd%28v=vs.120%29.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900