从默认参数推断模板参数 [英] Infer template argument from default parameter

查看:95
本文介绍了从默认参数推断模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#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 的类型:

The first two calls are fine, but it seems to be forbidden to let the compiler infer the type of COMP from the default parameter:

<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',而我却怀疑不允许这样做。

Am I missing something? I dont really understand why the compiler "couldn't infer template argument 'COMP'" and I rather suspect that it is not allowed to do so.

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

推荐答案

我建议像在标准C ++容器中那样进行操作地图或集合。它可以推断类型,还可以使用默认参数:

I'd suggest doing it the way it is done in standard C++ containers like map or set. It allows to infer the type and also allows to use default argument:

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

这篇关于从默认参数推断模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆