可以推断模板函数中的参数类型吗?

时间:2019-06-25 16:24:36

标签: c++ templates c++17 auto c++-concepts

我正在用C ++编写一些模板函数,但是我不确定是否可以定义一个推断其参数类型的模板函数。

我试图用推断的参数类型定义模板,但此示例无法编译:

template <auto>   
auto print_stuff(auto x, auto y) 
{ 
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}

当我为每种参数类型赋予唯一名称时,它可以工作,但这似乎有些多余:

#include <iostream> 
#include <string>

template <class Redundant_1,class Redundant_2>   
auto print_stuff(Redundant_1 x, Redundant_2 y) 
{ 
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}

int main() 
{ 
    print_stuff(3,"Hello!");
    return 0; 
}

是否可以使用推断的参数类型定义模板,而不是为每种类型赋予唯一的名称?

1 个答案:

答案 0 :(得分:3)

如果编译器支持概念,则可以省去参数类型的模板头和名称,即使要求使用实验性的C ++ 2a模式,该概念通常也不会启用。
例如,在gcc上,必须分别使用-fconcepts启用它。

请参见live on coliru

#include <iostream> 
#include <string>

auto print_stuff(auto x, auto y) 
{ 
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}

int main() 
{ 
    print_stuff(3,"Hello!");
    return 0; 
}

顺便说一句,请避免使用std::endl,并在极少数情况下不能避免使用昂贵的手动冲洗,请使用std::flush。另外,return 0;对于main()是隐式的。