【问题标题】:"No matching function for call" with variadic templates带有可变参数模板的“没有匹配的调用函数”
【发布时间】:2012-01-18 01:26:36
【问题描述】:

我有一个旨在动态加载.dll.so 或等效项的类。从那里,它将返回指向您要查找的任何函数的指针。不幸的是,我在实施过程中遇到了两个问题。

  1. 如果我使用返回 void* 的“哑”函数作为指向函数的指针,当我尝试将它们操作为我可以使用的形式时,我会得到 warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object
  2. 如果我尝试使用带有可变参数模板和类型安全的“智能”函数,我无法编译它。 error: no matching function for call to ‘Library::findFunction(std::string&)’ 是这里唯一等待我的东西。从下面的代码中可以看出,这应该与函数签名匹配。编译完成后,问题 1 也会出现在这里。

作为参考,我在Ubuntu 10.10 x86_64g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 下编译。我也尝试过使用g++-4.5 (Ubuntu/Linaro 4.5.1-7ubuntu2) 4.5.1 进行编译,但这并没有改变任何东西。

#include <string>
#include <stdio.h>

class Library
{
public:
    Library(const std::string& path) {}
    ~Library() {}

    void* findFunction(const std::string& funcName) const
    {
        // dlsym will return a void* as pointer-to-function here.
        return 0;
    }

    template<typename RetType, typename... T>
    RetType (*findFunction(const std::string& funcName))(T... Ts) const
    {
        return (RetType (*)(...))findFunction(funcName);
    }

};

int main()
{
    Library test("/usr/lib/libsqlite3.so");

    std::string name = "sqlite3_libversion";
    const char* (*whatwhat)() = test.findFunction<const char*, void>(name);
    // this SHOULD work. it's the right type now! >=[

    //const char* ver3 = whatwhat();
    //printf("blah says \"%s\"\n", ver3);
}

【问题讨论】:

    标签: c++ c++11 function-pointers variadic-templates dynamic-loading


    【解决方案1】:

    我认为您需要将返回的函数签名更改为 T... 而不仅仅是 ... 否则它需要一个变量 arglist 即使它应该是空的。

    template<typename RetType, typename... T>
    RetType (*findFunction(const std::string& funcName))(T... Ts) const
    {
        return (RetType (*)(T...))findFunction(funcName);
    }
    

    然后在类型列表中不带void 的情况下调用它,它应该可以工作:

    const char* (*whatwhat)() = test.findFunction<const char*>(name);
    

    通过这些更改,它可以在 gcc-4.5.1:http://ideone.com/UFbut 上为我编译

    【讨论】:

    • 哇,谢谢!这解决了我列表中的第二个问题。你知道我如何绕过关于在指针到对象和指针到函数之间转换的警告吗?
    • 有趣的是,一点点网络搜索表明第一个问题可能无法修复:trilithium.com/johan/2004/12/problem-with-dlsym - 这是一个旧链接,但我认为这种行为没有改变。
    • 是的,我自己刚刚发现了那篇文章。我认为我对此无能为力,这只是 GCC 会生成工作代码但无论如何都会抱怨的事情。那篇文章还提到了 Windows 上类似但相反的问题,所以我认为无论我做什么,这都会是一个问题。鉴于此,非常感谢您帮助我解决困扰我好几天的问题:)
    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多