2017-07-19 71 views
1

我有这样的功能:如何使用模板中的参数调用模板化函数?

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: 

为什么?

+2

将分隔符作为模板参数而不是函数参数的目的是什么?为什么不'template void split(T const&sep){...}'? –

+0

@Someprogrammerdude学习目的 – TheLogicGuy

回答

8

Why?

因为第一个模板参数是一个类型,而不是一个值。 'f'是字符常量,一个值。你不能插入一个类型。

正确的呼叫将是split<char, 'f'>()

在即将到来的C++标准17,你其实可以重新定义模板的方式,让你想要的语法:

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

现在通话将split<'f'>()演绎的sep类型。

+0

好用C++ 17'template '... :-) – WhiZTiM

+0

是否可以定义一个函数,用这个命令调用'split <'c'>(“ABcDEcA”)'? – TheLogicGuy

+0

@ TheLogicGuy - 是的。 'template void split(std :: string const&){}' – StoryTeller