Smoothing the variational function of a template

I have a variational 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 add an alias 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 does not work with variable functions because it needs placeholders ...

Is it possible to use a pseudo-random function?

+6
source share
3 answers

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 variational function and the std::forward arguments:

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

What you are trying is not much different from

 void test(int) { } void test(double, int) { } auto a = test; 

The compiler cannot determine which overload you want to use.

You can specify for which test you want to assign a :

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

If you want to add a version of a variation template 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>; 
+1
source

This is not smoothing. auto a = test tries to declare a variable of the same type as test , and make them equal. Since the test is not just one function, but a function template (and, first of all, you can even overload functions), the compiler cannot decide what type should be.

For a template alias or, in fact, any character, you can use the using keyword.

 using a = test; 

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

0
source

Source: https://habr.com/ru/post/971106/


All Articles