![](/img/trans.png)
[英]Why does using the default template parameter for a function also used in a lambda parameter not work
[英]Why does not work with lambda with template
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 與模板一起使用的正確方法是什么以及如何解決此問題?
As a template argument std::greater<int>()
is parsed as a function type (a function that takes no arguments and returns the class type std::greater<int>
). 這是您可以使用大括號幫助編譯器區分的地方:
auto h = bind2nd.template operator()<std::greater<int>{}, 5>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.