gpt4 book ai didi

c++ - 从默认参数推断模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:21 25 4
gpt4 key购买 nike

考虑这段代码:

#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++ 容器(如 map 或 set)中的方式进行操作。它允许推断类型并允许使用默认参数:

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

关于c++ - 从默认参数推断模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com