【问题标题】:Infer template argument from default parameter从默认参数推断模板参数
【发布时间】: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


    【解决方案1】:

    我建议按照标准 C++ 容器(如 map 或 set)中的方式进行操作。它允许推断类型并允许使用默认参数:

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

    【讨论】:

    • @LuisMachuca 您希望它如何与&gt;&gt; 运算符一起使用?
    • 点,我在想一个class定义。
    【解决方案2】:

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

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

    【讨论】:

    • 应该是std::less&lt;T&gt;,不是吗?
    • std::less&lt;&gt; 在 C++98 中不可用。
    • 好吧,我忽略了标签...感谢您的提示,我会修复它。
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多