【问题标题】:assinging a c++ function object to c function pointer [duplicate]将c ++函数对象分配给c函数指针[重复]
【发布时间】:2014-06-21 19:27:14
【问题描述】:

我不知道这是否可以做到。由于我的一个函数需要将函数对象传递给 c 库函数,并且它只能采用函数指针。

我创建了一个演示程序,我认为它足以说明我的目的:

#include <iostream>
#include <functional>
class Test;

void init_class(std::function<int (int)> fn) {
  int (*new_fn)(int) = nullptr; // I can't assign fn to new_fn either <<<<<<<<<<<<
  new_fn = fn;  // this complains <<<<<<<<<<<<<<<<<<<<<<<<<
  std::cout << new_fn(199) << std::endl;
}

class Test {
 public:
  explicit Test()
      : n_(199) {
  }
  ~Test() noexcept {}

  int calculate(int val) {
    return n_ + val;
  }

  void run() {
    std::function<int (int)> fn =
      std::bind(&Test::calculate, this, std::placeholders::_1);
    init_class(fn);
  }

 private:
  int n_;
};

void test() {
  Test a;
  a.run();
}

int main(int argc, const char *argv[]) {
  test();
  return 0;
}

【问题讨论】:

标签: c++ function stl


【解决方案1】:

我遇到了同样的问题 - 看看下面的链接,有几个有趣的答案:
Convert C++ function pointer to c function pointer
简而言之,您不能将函数指针分配给非静态 C++ 成员函数。您可以做的是创建一个使用实例参数进行调用的静态或全局函数,请查看上面的链接了解更多详细信息。

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2018-08-24
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多