[英]why the template argument deduction/substitution failed in the code?-
I am using compiler g++ 6.3.0 (c++14). 我使用的是编译器g ++ 6.3.0(c ++ 14)。 In the code-
在代码中 -
#include<iostream>
int f(auto a){return a;}
int f1(auto (*g)(int),int a) {return g(a);}
main()
{
std::cout<< f1(f,8);
}
Compiler is not able to deduce the return type of g. 编译器无法推断出g的返回类型。 It shows following error-
它显示以下错误 -
temp.cpp: In function 'int main()':
temp.cpp:9:20: error: no matching function for call to 'f1(<unresolved overloaded function type>, int)'
std::cout<< f1(f,8);
^
temp.cpp:5:5: note: candidate: template<class auto:2> int f1(auto:2 (*)(int), int)
int f1(auto (*g)(int),int a) {return g(a);}
^~
temp.cpp:5:5: note: template argument deduction/substitution failed:
temp.cpp:9:20: note: couldn't deduce template parameter 'auto:2'
std::cout<< f1(f,8);
^
But no error comes in the code- 但是代码中没有错误 -
#include<iostream>
int f(int /* <<<<< */ a){return a;} // only (auto a) is changed to (int a)
int f1(auto (*g)(int),int a) {return g(a);}
main()
{
std::cout<< f1(f,8);
}
Help me understand the error... 帮我理解错误......
int f(auto a){return a;}
is equivalent to 相当于
template <typename T>
int f(T a){return a;}
You cannot take the address of a template (or overload set) - that is why you're seeing that error. 你不能获取模板的地址(或重载集) - 这就是你看到错误的原因。 Workarounds:
解决方法:
Take the address of the instantiation you want: 获取所需实例化的地址:
return f1(f<int>,8);
Make f1
accept auto
and pass a lambda: 使
f1
接受auto
并传递lambda:
int f1(auto g, int a) {return g(a);} int main() { std::cout<< f1([](auto x){ f(x); },8); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.