【发布时间】:2020-05-27 02:45:18
【问题描述】:
auto bind2nd = [] < auto func_object,auto second_arg>(){
return [=](auto&& first_arg){
return func_object(first_arg,second_arg);
};
};
auto h =bind2nd.template operator()<std::greater<int>(),5>();
编译结果:
<source>:9:60: error: no matching function for call to '<lambda()>::operator()<std::greater<int>(), 5>()'
9 | auto x =bind2nd.template operator()<std::greater<int>(),5>();
| ^
<source>:3:16: note: candidate: 'template<auto func_object, auto second_arg> <lambda()>'
3 | auto bind2nd = [] < auto func_object,auto second_arg>(){
| ^
<source>:3:16: note: template argument deduction/substitution failed:
<source>:9:60: error: type/value mismatch at argument 1 in template parameter list for 'template<auto func_object, auto second_arg> <lambda()>'
9 | auto x =bind2nd.template operator()<std::greater<int>(),5>();
| ^
<source>:9:60: note: expected a constant of type 'auto', got 'std::greater<int>()'
<source>:9:60: note: ambiguous template argument for non-type template parameter is treated as function type
我想将 lambda 与模板一起使用,但它不起作用。
但我可以运行它:
auto x =[]<auto t>(){
return t;
};
auto test = []<auto func_object,auto second_arg>(){
return [=](auto&& first_arg){
return func_object.template operator()<second_arg>();
};
};
auto z =test.template operator()<x,5>();
int main(){
std::cout<<z(5);
}
它将打印 5。
在模板中使用 lambda 的正确方法是什么以及如何解决这个问题?
【问题讨论】:
-
我认为不能保证
std::greater可以用作非类型模板参数类型。 -
@TedLyngmo:是的,谢谢你的回答。
标签: c++ templates lambda c++20