通过C ++函数对象类访问参数

时间:2017-07-12 12:18:52

标签: c++ c++11

    #include <iostream>

    struct A {
        explicit A(int a) : _a(a) {};
        int _a;
    };

    struct ClassFunction {
        ClassFunction(std::shared_ptr<A> myA) : _myA(myA) {}

        double operator() (int &x,
                           int &g) {
            return 1.0
                   + static_cast<double>(_myA->_a); // offending line
        }
        static double wrap(int x, int g, void *data) {
            return (*reinterpret_cast<ClassFunction*>(data)) (x,g);
        }
        std::shared_ptr<A> _myA;
    };

    int main() {
        int x = 1;
        int g;
        auto myA = std::shared_ptr<A>(new A(int(20)));
        ClassFunction myClassFunction(myA);
        std::cout << ClassFunction::wrap(x,g,NULL) << std::endl;
        return 0;
    }

我尝试创建一个以ClassFunction为参数的函数对象类std::shared_ptr<A>,然后通过static成员函数ClassFunction::wrap调用该参数。

如果我将A的数据成员作为myA->_a访问,则该程序无法运行(但它会在没有任何投诉的情况下进行编译)。

我如何使这项工作?

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

std::cout << ClassFunction::wrap(x, g, &myClassFunction) << std::endl;

的reinterpret_cast&LT;当数据指向ClassFunction类的实例时,ClassFunction *&gt;(data)适用。

相关问题