繁体   English   中英

如何使用模板中的参数调用模板化函数?

[英]How to call a templated function with a parameter in the template?

我有这个功能:

template <typename T, T sep>
void split (){
    std::cout << sep << std::endl;    
}

当我尝试使用以下命令调用它时: split<'f'>();
我收到以下错误:

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:

为什么?

为什么?

因为第一个模板参数是类型,而不是值。 'f'是字符常量,是一个值。 而且您不能将其插入某种类型。

正确的调用应该是split<char, 'f'>()

实际上,在即将发布的C ++ 17标准中,您实际上可以以允许所需语法的方式重新定义模板:

template <auto sep>
void split (){
    std::cout << sep << std::endl;    
}

现在,调用split<'f'>()将推断出sep的类型。

暂无
暂无

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

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