c++ - 为什么代码中的模板参数扣除/替换失败?-
问题描述
我正在使用编译器 g++ 6.3.0 (c++14)。在代码中 -
#include<iostream>
int f(auto a){return a;}
int f1(auto (*g)(int),int a) {return g(a);}
main()
{
std::cout<< f1(f,8);
}
编译器无法推断 g 的返回类型。它显示以下错误 -
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);
^
但是代码中没有错误-
#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);
}
帮助我理解错误...
解决方案
int f(auto a){return a;}
相当于
template <typename T>
int f(T a){return a;}
您不能获取模板(或重载集)的地址 - 这就是您看到该错误的原因。解决方法:
获取所需实例化的地址:
return f1(f<int>,8);
f1
接受auto
并传递一个 lambda :int f1(auto g, int a) {return g(a);} int main() { std::cout<< f1([](auto x){ f(x); },8); }
推荐阅读
- r - 将具有不同时区的时间字符向量转换为R中的UTC
- java - 为什么 Java 的 Optional.of() 不接受空值?那时它不再是真正的“可选”值
- python - 将变量设置为 var=var=value 可以吗?
- bash - Bash 没有正确设置换行
- python-3.x - 如何正确导入我创建的 python 模块?
- python - 如何在 Python Kivy 的 TextInput 字段中显示希伯来语文本
- javascript - ES2015+ way to efficiently transform array of objects into grouped hashmap with array of objects as value
- php - 为什么 .env 文件优先于 .yaml 文件作为环境变量?
- javascript - 使用用于服务器端应用程序的 Google Drive API 授予对单个文件的读取权限
- python - 使 Boto3 上传调用阻塞(单线程)