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

标签 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; 
}

是否可以使用推断的参数类型来定义模板,而不是给每个类型一个唯一的名称?

最佳答案

如果您的编译器支持概念,您可以省去模板头和参数类型的名称,即使要求实验性 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() 是隐含的。

关于c++ - 模板函数中的参数类型可以推断吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56758349/

相关文章:

c++ - 在模板化类中定义模板化类的静态数据成员

c++ - std::ostringstream 覆盖初始化字符串

c++ - 如何将几个 bool 标志包装到结构中以将它们传递给具有方便语法的函数

c++ - 模板内嵌套类型名称的流运算符重载

c++ - b2 vs bjam 用于构建 Boost 库

c++ - 使用 runge_kutta4 的高维数组

c++ - int8_t 和 int64_t 的最小值

内联函数的 C++ 作用域

c++ - 如果推导其中一个模板参数,是否可以不指定所有模板参数?

c++ - 如何将<map>存储在<vector>中?