可以推断模板函数中的参数类型吗? [英] Can the types of parameters in template functions be inferred?
问题描述
我正在用C ++编写一些模板函数,但是我不确定是否可以定义一个推断其参数类型的模板函数.
I'm writing some template functions in C++, but I'm not sure if it's possible to define a template function that infers the types of its parameters.
我试图用推断的参数类型定义模板,但是此示例无法编译:
I tried to define a template with inferred parameter types, but this example won't compile:
template <auto>
auto print_stuff(auto x, auto y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
当我为每种参数类型赋予唯一名称时,它可以工作,但这似乎有些多余:
It works when I give a unique name to each parameter type, but this seems somewhat redundant:
#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;
}
是否可以使用推断的参数类型定义模板,而不是为每种类型赋予唯一的名称?
Is it possible to define a template with inferred parameter types instead of giving each type a unique name?
推荐答案
如果您的编译器支持概念,则可以省去模板头和参数类型的名称,即使要求实验性C,通常也不会启用这些概念++ 2a模式.
例如,在gcc上,必须分别使用-fconcepts
启用它.
You can dispense with the template-header and names for the parameter-types if your compiler supports concepts, which isn't generally enabled even if asking for experimental C++2a mode.
On gcc for example, it must be separately enabled with -fconcepts
.
请参见在大肠上生活.
#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()
是隐式的.
As an aside, avoid std::endl
and use std::flush
in the rare cases you cannot avoid costly manual flushing. Also, return 0;
is implicit for main()
.
这篇关于可以推断模板函数中的参数类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!