从默认参数推断模板参数

时间:2018-08-07 09:43:24

标签: c++ templates c++98 default-parameters

考虑以下代码:

#include <functional>

template <typename T,typename COMP>
bool foo(T a,T b,COMP c = std::less<T>()) { 
    return c(a,b); 
}

bool bar(int a, int b){ return a<b;}

int main(){
    foo(1,2,bar);               // OK
    foo(1,2,std::less<int>());  // OK
    foo(1,2);                   // error
}

前两个调用很好,但是似乎不允许编译器从默认参数推断COMP的类型:

<source>:14:5: error: no matching function for call to 'foo'    
    foo(1,2);    
    ^~~    
<source>:4:6: note: candidate template ignored: couldn't infer template argument 'COMP'    
bool foo(T a,T b,COMP c = std::less<T>()) {    
     ^   
1 error generated.    
Compiler returned: 1

我想念什么吗?我真的不明白为什么编译器“无法推断模板参数'COMP'”,而我却怀疑不允许这样做。

是否可以从默认参数推断出模板参数?如果没有,为什么?

2 个答案:

答案 0 :(得分:9)

我建议这样做,就像在标准C ++容器(例如map或set)中那样进行。它可以推断类型,还可以使用默认参数:

template <typename T,typename COMP = std::less<T>>
bool foo(T a,T b, COMP c = COMP()) { /* As before. */ }

答案 1 :(得分:2)

无法推断类型。您也可以手动指定默认类型:

template <typename T,typename COMP = std::less<T>>
bool foo(T a,T b,COMP c = std::less<T>()) { /* As before. */ }