简体   繁体   English

别名可变参数模板函数

[英]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 ... 我尝试使用std::bind但它不适用于可变参数函数,因为它需要占位符...

Is it possible to alias a variadic function ? 是否可以为可变参数函数添加别名?

In C++1y : 在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 : 或者将其包装在另一个可变参数函数中并且std::forward参数:

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

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: 你可以明确了解哪些test你要分配给a人:

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>;

This is not aliasing. 这不是别名。 auto a = test tries to declare a variable a with the same type as test and make them equal. auto a = test尝试声明一个与test类型相同的变量a并使它们相等。 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关键字。

using a = test;

Edit: sorry this one only works for types not functions. 编辑:对不起,这个只适用于不是函数的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM