c++ - 尝试将函数作为参数传递时未解析的重载函数类型

标签 c++ function templates c++11 variadic-templates

尝试在 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/

相关文章:

r - 执行库(pkg)后执行包中的函数

c++ - 让编译器在编译前推断出函数的参数

C++ atoi 返回不正确的值

c++ - 在 map 中就地构建不可 move 的对象

c++ - 类 : handling copy constructor and destructor (C++) 内的 vector

c++ - 如何制作可移植 isnan/isinf 函数

c++ - 令我惊讶的是,这段代码可以正确编译和执行。这里发生了什么事?

c++ - 为什么这个模板递归无法编译?

c++ - 从基类调用派生类的函数模板

c++ - 是否存在定时指针?