Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing variadic macros or templates to implement a set of functions
    primarykey
    data
    text
    <p>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 <strong>Init</strong> function :</p> <pre><code>ObjectType* CreateObjectType(Arg1 a1, Arg2 arg2, ... ArgN aN) { ObjectType* object = new ObjectType(); [...] object-&gt;Init(this, a1, a2, ..., aN); [...] return object; } </code></pre> <p>Note that the arguments are not to be used anywhere except to be passed to the <strong>Init</strong> function.</p> <p>I would like to find a way to implement all of those without having to duplicate the code for each object type. </p> <hr> <p>I tried using variadic macros, with the following (invalid) result :</p> <pre><code>#define CREATE_OBJECT_IMPL(ObjectType, ...) \ ObjectType* Create##ObjectType##(__VA_ARGS__) \ { \ ObjectType* object = new ObjectType(); \ [...] object-&gt;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) </code></pre> <p>Now, in this implementation, I used VA_ARGS twice, both times incorrectly :</p> <ul> <li><p>In the first case, I want to have a list of arguments with the types I specified (Arg1 a1, Arg2 a2...)</p></li> <li><p>In the second case, I want to call these arguments by their names ( Init(a1, a2...) ). </p></li> </ul> <hr> <p>I tried using variadic templates :</p> <pre><code>template&lt; typename ObjectType, typename... Args &gt; ObjectType* CreateObject(Args args) { ObjectType* object = new ObjectType(); [...] object-&gt;Init(this, args); [...] return object; } #define CREATE_OBJECT_IMPL(ObjectType, ...) \ ObjectType* Create##ObjectType##(__VA_ARGS__) \ { \ return CreateObject&lt;ObjectType, __VA_ARGS__&gt;(__VA_ARGS__); \ } </code></pre> <p>...but this doesn't seem to work as well, I get the following error on the template definition line :</p> <blockquote> <p>error C2143: syntax error : missing ',' before '...'</p> <p>error C2065: 'Args' : undeclared identifier</p> </blockquote> <p>I am using VS2012.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload