I am instantiating various objects based on an xml file. To create an object from a template I specify the datatype in the xml file. As I have quite a lot of templates and datatypes that should be supported I'd like to condense my code a little bit. I thought I could do this by using macros, but since I never really used to them, I have no idea how to do this. By providing a list of datatypes I'd like to support I thought I could simply write
MACRO(A, dataTypes)
instead of:
if(s == "float")
{
return new A<float>(name);
}
else if(s == "int")
{
return new A<int>(name);
}
else if(s == "bool")
{
return new A<bool>(name);
}
else if(s == "std::string")
{
return new A<std::string>(name);
}
...
But how can I define a 开发者_Python百科macro like that? The code should compile on Android as well, so it should not rely on another library like boost.
The macro would be something like:
#define MACRO(T) if (s == #T) { return new A<T>(blockName); }
You only need a parameter (the type), because as far as I can see, A
is fixed in your code.
If you want to create the code for several types at once, this is not that easy. You should use something like boost preprocessor.
精彩评论