【发布时间】: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;
}
【问题讨论】:
-
这是不可能的。你可以使用一个普通函数来读取你希望它拥有的任何状态的全局变量,但就是这样。