c++ - 如何将类方法传递给另一个函数,就像线程构造函数中发生的那样

标签 c++ function-pointers argument-passing

我想将一个类方法传递给另一个函数,我写了这些代码:

class x {
   executeQuery(std::string query, int (*f)(void* cpuInfo, int argc, char** argv, char** azColName))
   {
          int rc = sqlite3_exec(db, query.c_str(), &f, 0, &errMessage);
          ...
   }
};

上面的代码显示了我从类构造函数中调用的函数!

myclass()
{
    xObject->executeQuery("test", &(myclass::myfunction));
}

这部分代码展示了我如何将 myfunction 传递给那个方法!但是,在编译期间我得到了这个错误:

error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.

我用相同的语法调用了线程构造函数!但是好像thread构造器make了一个我看不懂的new函数指针!你知道我如何使用/不使用线程解决方案来解决这个问题吗? 下面的代码显示了线程构造函数头:

  template<typename _Callable, typename... _Args>
  explicit 
  thread(_Callable&& __f, _Args&&... __args)
  {
    _M_start_thread(_M_make_routine(std::__bind_simple(
            std::forward<_Callable>(__f),
            std::forward<_Args>(__args)...)));
  }

最佳答案

更新:

在您的示例中,您将函数指针与 sqlite3_exec 一起使用。 sqlite3_exec 需要一个 C 风格的函数作为参数 callback。您可以在此处使用指向类成员函数的指针!

像这样的事情可能是一种解决方法。但要注意线程安全:

namespace wrap {
    typedef std::function<int(void*,int,char**,char**)> QueryFunction;
    inline QueryFunction& function() {
        static QueryFunction f;
        return f;
    }
    void callback(void* cpuInfo, int argc, char** argv, char** azColName);
}

void wrap::callback(void* cpuInfo, int argc, char** argv, char** azColName) {
     function()(cpuInfo, argc, argv, azColName);
}


class x {
   executeQuery(std::string query, QueryFunction f)
   {
        wrap::function() = f;
        int rc = sqlite3_exec(db, query.c_str(), &wrap::callback, 0, &errMessage);
        ...
   }
};

MyClass* obj = ...;
xObject->executeQuery("test", std::bind(myclass::myfunction, obj));

旧答案:

您可以使用 std::function 来包装类成员函数(参见 here ):

#include <functional>

typedef std::function<int(void*,int,char**,char**)> QueryFunction;

class x {
public:
    void executeQuery(std::string query, QueryFunction f) {
        f(ptr,0,"hello","test"); // call function
    }
};

MyClass* obj = ...;
using std::placeholders;
xObject->executeQuery("test", std::bind(myclass::myfunction, obj, _1, _2, _3, _4));

为了给出一个指向类成员函数的指针,您还需要提供一个应该调用该成员函数的对象。

std::bind 允许您这样做(甚至更多)。在上面的例子中,std::bind 的第一个参数是指向类成员函数的指针,第二个参数是用于调用该函数的对象。以下参数 _1, ... 是您稍后在使用函数指针时提供的参数的占位符。

关于c++ - 如何将类方法传递给另一个函数,就像线程构造函数中发生的那样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22909459/

相关文章:

R:找到作为参数传递的函数的原始名称

python - 如何将相同的参数解析两次或多次到 python 脚本?

c++ - `non-deducible`的正式定义是什么

c++ - find_if 错误 : invalid initialisation of reference of type 'const node&' from expression of type 'node*'

rust - 如何将泛型函数转换为带有引用参数的函数指针?

c++ - pthread_create() 调用的函数的多个参数 - 参数是函数指针

c++ - 数组作为参数

c++ - OpenGL Performer 最简单的移植路径?

c++ - 忽略 GCC "error: braces around scalar initializer for type"错误。让他们警告

c++ - 是否可以通过 lambda 将变量模板传递给函数?