I have a set of methods used to instanciate and initialize a set of objects. They all look pretty much the same, except for the number of arguments that are passed to the Init function :
ObjectType* CreateObjectType(Arg1 a1, Arg2 arg2, ... ArgN aN)
{
ObjectType* object = new ObjectType();
[...]
object->Init(this, a1, a2, ..., aN);
[...]
return object;
}
Note that the arguments are not to be used anywhere except to be passed to the Init function.
I would like to find a way to implement all of those without having to duplicate the code for each object type.
I tried using variadic macros, with the following (invalid) result :
#define CREATE_OBJECT_IMPL(ObjectType, ...)
ObjectType* Create##ObjectType##(__VA_ARGS__)
{
ObjectType* object = new ObjectType();
[...]
object->Init(this, ##__VA_ARGS__);
[...]
return object;
}
// This is the result I am trying to achieve :
CREATE_OBJECT_IMPL(MyFirstObject, bool, float)
CREATE_OBJECT_IMPL(MySecondObject, int)
CREATE_OBJECT_IMPL(MyThirdObject)
Now, in this implementation, I used VA_ARGS twice, both times incorrectly :
In the first case, I want to have a list of arguments with the types I specified (Arg1 a1, Arg2 a2...)
In the second case, I want to call these arguments by their names ( Init(a1, a2...) ).
I tried using variadic templates :
template< typename ObjectType, typename... Args >
ObjectType* CreateObject(Args args)
{
ObjectType* object = new ObjectType();
[...]
object->Init(this, args);
[...]
return object;
}
#define CREATE_OBJECT_IMPL(ObjectType, ...)
ObjectType* Create##ObjectType##(__VA_ARGS__)
{
return CreateObject<ObjectType, __VA_ARGS__>(__VA_ARGS__);
}
...but this doesn't seem to work as well, I get the following error on the template definition line :
error C2143: syntax error : missing ',' before '...'
error C2065: 'Args' : undeclared identifier
I am using VS2012.
I could still write N similar macros for each number of arguments, however I was wondering if there was a way to obtain the same result without duplicating code?
See Question&Answers more detail:os