Search code examples
c++variadic-templates

How to create function-template, that expands parameter-pack which doesn't represent function argument(s)?


I apologize, but I had a big problem in expressing the case in one sentence of the title.

The problem: I have a class template based on many "properties" (don't take this "property" keyword too literally):

template<typename ... P>
class C: public P... {}

Then I want separate, free function template that takes two instances and performs some call for each "property":

template<typename ... P>
void foo(C<P> &c1, C<P> &c2)
{
    { doSomething<p>()... }      // for each type p in pack P
}

template<typename T>
void doSomething() {}

The problem is that P doesn't represent a set of my function arguments. Instead it parametrizes argument types. So I don't know how to write "expansion". Is such thing possible at all?


Solution

  • It seems to me that you are just missing the parameter pack expansion in the function parameters. Then there is also a small typo (p->P) and you seem to intend to use a fold-expression to execute the function for all types which has a slightly different syntax:

    template<typename ... P>
    void foo(C<P...> &c1, C<P...> &c2)
    {
        // Parentheses and comma required to signify fold expression using the comma operator
        ( doSomething<P>(), ... ); 
    }
    

    I also feel like you would want to pass c1 and c2 on to doSomething (which probably should be taking he objects as T&, I guess?), otherwise that function will depend only on the type, not an actual object of that type.