[英]How to call a templated function with a parameter in the template?
I've this function: 我有这个功能:
template <typename T, T sep>
void split (){
std::cout << sep << std::endl;
}
When I try to call it with this command: split<'f'>();
当我尝试使用以下命令调用它时: split<'f'>();
I get the following error: 我收到以下错误:
q3.cpp: In function ‘int main()’:
q3.cpp:36:16: error: no matching function for call to ‘split()’
split<'f'>();
^
q3.cpp:36:16: note: candidate is:
q3.cpp:31:6: note: template<class T, T sep> void split()
void split (){
^
q3.cpp:31:6: note: template argument deduction/substitution failed:
Why? 为什么?
Why? 为什么?
Because the first template parameter is a type, not a value. 因为第一个模板参数是类型,而不是值。 'f'
is character constant, a value. 'f'
是字符常量,是一个值。 And you cannot plug it in for a type. 而且您不能将其插入某种类型。
A correct call would be split<char, 'f'>()
. 正确的调用应该是split<char, 'f'>()
。
In the upcoming C++17 standard, you can in fact redefine your template in a way that allows the syntax you want: 实际上,在即将发布的C ++ 17标准中,您实际上可以以允许所需语法的方式重新定义模板:
template <auto sep>
void split (){
std::cout << sep << std::endl;
}
Now the call split<'f'>()
will deduce the type of sep
. 现在,调用split<'f'>()
将推断出sep
的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.