【发布时间】:2018-08-07 09:43:24
【问题描述】:
考虑这段代码:
#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'”,我宁愿怀疑它不允许这样做。
是否可以从默认参数推断模板参数?如果不是,为什么?
【问题讨论】:
标签: c++ templates c++98 default-parameters