Is there a way to pass
std::map<std::string, float>
as an argument to a macro?
(the problem is that the "," is used by the macro to split
std::map<std::string
and
float>
as separate arguments. I would like to avoid this.
A macro template and its macro expansion are separated by blanks or tabs. A space between # and define is optional. A macro definition is never to be terminated by a semicolon. In C programming it is customary to use capital letters for macro template.
A macro is a recording of formatting changes and other steps that can be replayed quickly. A template is a pre-formatted spreadsheet with headers and formulas – awaiting your data.
Macros are expanded by preprocessor, before compilation proper; templates are expanded at compile time. Macros are always expanded inline; templates can also be expanded as inline functions when the compiler deems it appropriate. Thus both function-like macros and function templates have no run-time overhead.
Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.
In C, the only native means of creating static templates are through the use of macros. printf("%d", foo); The DEF macro described above can work with any type which can be initialized via the = operator.
No, there isn't a way to do this, short of using a typedef. BOOST_FOREACH, for example, suffers the same problem.
Try to use a template instead of the macro.
Scott Meyers : Effective C++ Item 2: Prefer consts, enums, and inlines to #defines
Yes there is a way, it's indirect though.
As you have said, a macro is rather dumb in its interpretation. However it still recognize parenthesis.
Example: BOOST_MPL_ASSERT((boost::is_same<int,int>))
It works by using another level of parenthesis, thus forming a Tuple
(from the macro point of view).
If you use the Boost.Preprocessor library, you can easily "unwrap" a Tuple
to get its content unscathed. Unfortunately you are supposed to know the size of a tuple upfront, so you need an additional parameter
#define MY_MACRO(Size, TemplatedType, Name)\
BOOST_PP_TUPLE_REM(Size)(TemplatedType) Name
And in action:
MY_MACRO(2, (std::map<int,std::string>), idToName);
// expands to 'std::map<int,std::string> idToName'
idToName[1] = "Smith";
So, yes it is possible, but the macro has to be explicitly tailored to handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With