uchar
uchar

Reputation: 2590

aliasing a variadic template function

I have a variadic function like :

void test(int){}

template<typename T,typename...Args>
void test(int& sum,T v,Args... args)
{
    sum+=v;
    test(sum,args...);
}

I want to alias it to something like :

auto sum = test;//error : can not deduce auto from test
int main()
{
    int res=0;
    test(res,4,7);
    std::cout<<res;
}

I tried using std::bind but it doesn't work with variadic functions because it needs placeholders ...

Is it possible to alias a variadic function ?

Upvotes: 6

Views: 1158

Answers (3)

Evan Dark
Evan Dark

Reputation: 1341

This is not aliasing.auto a = test tries to declare a variable a with the same type as test and make them equal. Since test isn't a single function, but a function template (and on the top of that you can even overload functions), the compiler can't decide on what the type of a should be.

To alias a template, or as a matter of fact any symbol, you can use the using keyword.

using a = test;

Edit: sorry this one only works for types not functions.

Upvotes: 0

Drax
Drax

Reputation: 13278

In C++1y :

#include <iostream>

void test(int){}

template<typename T,typename...Args>
void test(int& sum,T v,Args... args)
{
  sum+=v;
  test(sum,args...);
}

template<typename T,typename...Args>
decltype(test<T, Args...>)* sum = &(test<T, Args...>);

int     main(void)
{
  int   res = 0;
  sum<int, int>(res, 4, 7);
  std::cout << res << std::endl;
}

Alternatively wrap it in another variadic function and std::forward the arguments :

template<typename T,typename...Args>
void    other(int&sum, T v, Args&&... args)
{
  test(sum, std::move(v), std::forward<Args>(args)...);
}

Upvotes: 4

R Sahu
R Sahu

Reputation: 206567

What you are trying is not much different from

void test(int)
{
}

void test(double, int)
{
}

auto a = test;

There is no way for the compiler to detect which overload you want to use.

You can be explicit about which test you want to assign to a by:

auto a = (void(*)(int))test;

If you want to add the variadic template version to the mix, you can use:

template<typename T,typename...Args>
void test(int& sum,T v,Args... args)
{
    sum+=v;
    test(sum,args...);
}

auto a = test<int, int, int>;

Upvotes: 1

Related Questions