【问题标题】:Unresolved overloaded function type when attempting to pass a function as an argument尝试将函数作为参数传递时未解析的重载函数类型
【发布时间】:2016-03-14 10:15:36
【问题描述】:

尝试在 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 系统上构建此代码,此代码 sn-p 包含与此问题相关的所有代码。我特别感兴趣的是编译器由于某种原因无法推断出模板参数funcT,即使outputLine 函数具有明确的返回类型void。

使用void (*outputLinePtr)(std::string) = outputLine 设置outputLine 的指针并使用指针作为参数什么都不做。任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    您可以手动设置模板参数。

    callFunctionFromName (outputLine<std::string>, param);
    

    【讨论】:

    • 嗯,嗯,那行得通。我不知道为什么。你能给我一个链接或一些我能读到的关于这个&lt;&gt;语法的参考吗?我是 C++ 新手,很抱歉这个看似无知的问题。谢谢!
    • @Wintro 它只是函数的显式实例化。你告诉编译器,你想使用outputLine 类型std::string
    • 啊哈,好的,谢谢。有没有办法让它保持通用,即如果我想通过callFunctionFromName 将一个值传递给outputLine,直到通过的那一刻我才知道它的类型?
    • @Wintro 编译器不知道 outputLine 是什么函数,它只是&lt;unresolved overloaded function type&gt;。为什么不能在调用站点手动指定函数类型?
    • 哦,所以编译器无法弄清楚函数到底是什么,除非我指定我想要的重载?我现在明白了。谢谢你。我可以指定类型,但我只是在问一个一般性问题。
    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多