从默认参数中推断模板参数

for*_*818 4 c++ templates default-parameters c++98

考虑以下代码:

#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
}
Run Code Online (Sandbox Code Playgroud)

前两个调用很好,但似乎禁止让编译器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
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?我真的不明白为什么编译器"无法推断模板参数'COMP'",我宁愿怀疑它不允许这样做.

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

bar*_*top 9

我建议按照标准C++容器(如map或set)的方式完成它.它允许推断类型并允许使用默认参数:

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