尝试在 G++ 下使用 C++11 编译单独的 C++ 测试文件时收到以下错误。
spike/cur_spike.cpp: In function ‘int main()’:
spike/cur_spike.cpp:60:44: error: no matching function for call to ‘callFunctionFromName(<unresolved overloaded function type>, std::__cxx11::string&)’
callFunctionFromName (outputLine, param);
^
spike/cur_spike.cpp:49:7: note: candidate: template<class funcT, class ... Args> funcT callFunctionFromName(funcT (*)(Args ...), Args ...)
funcT callFunctionFromName (funcT func(Args...), Args... args) {
^
spike/cur_spike.cpp:49:7: note: template argument deduction/substitution failed:
spike/cur_spike.cpp:60:44: note: couldn't deduce template parameter ‘funcT’
callFunctionFromName (outputLine, param);
^
这是代码。
#include <iostream>
#include <string>
template <typename T>
void outputLine (T text) {
std::cout << text << std::endl;
}
template <typename funcT>
funcT callFunctionFromName (funcT func()) {
return func ();
}
template <typename funcT, typename... Args>
funcT callFunctionFromName (funcT func(Args...), Args... args) {
return func (args...);
}
int main () {
std::string param = "Testing...";
callFunctionFromName (outputLine, param);
return 0;
}
我目前正在使用 G++ 在 Linux 系统上构建它,此代码片段包含与此问题相关的所有代码。令我特别感兴趣的是,编译器出于某种原因无法推断出模板参数 funcT
,即使 outputLine
函数具有明确的 void 返回类型。
使用 void (*outputLinePtr)(std::string) = outputLine
设置 outputLine
的指针并将指针用作参数而不是不执行任何操作。任何帮助将不胜感激。
最佳答案
您可以手动设置模板参数。
callFunctionFromName (outputLine<std::string>, param);
关于c++ - 尝试将函数作为参数传递时未解析的重载函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35984735/