mardi 30 décembre 2014

How to pass variable arguments to Variadic template function in a right way C++

Hi I got a variadic templates in C++



int sum(int a, int b) { return a + b; }

template<typename Func, typename... Args>
auto MainCall(Func func, Args&&... args)-> typename std::result_of<Func(Args...)>::type
{
return func(std::forward<Args>(args)...);
}

template <typename... Args>
int call2(Args const&... args)
{
return MainCall(sum, args...); /* calling template function MainCall,
how to pass the variable arguments to
Maincall from here?
*/
}

int _tmain(int argc, _TCHAR* argv[])
{
cout << call2(4,5) << endl;
return 0;
}


Am I doing a right way of passing arguments? I get the compiler error like this

error C3520: 'args' : parameter pack must be expanded in this context

see reference to function template instantiation 'int call2(const int &,const int &)' being compiled


What is the correct way of passing variable arguments to the MainCall template?


Note: Parameters need to be always variable so that MainCall can take any function with any number of arguments.. Just for an example I have writen sum function here..


Aucun commentaire:

Enregistrer un commentaire