#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;
}
私はその後、static
メンバ関数ClassFunction::wrap
経由で呼び出すパラメータとしてstd::shared_ptr<A>
を取る関数オブジェクトクラスClassFunction
を作成しようとしています。C++の関数オブジェクトクラスを経由してパラメータにアクセスする
A
のデータメンバーにmyA->_a
としてアクセスすると、プログラムは実行されません(ただし、苦情なしでコンパイルされます)。
この作品を作成するにはどうすればよいですか?
'wrap'へのヌルポインタを渡さないようにすると効果がありますか? –
なぜあなたは 'ClassFunction :: wrap(x、g、NULL)'を書いていましたか?なぜあなたはそれが働くことを期待していますか? – Angew
最適化ライブラリ 'NLOPT'で提案されている定型コードと非常によく似ていますが、" ... 2行のヘルパー関数を使用しています。もしあなたの関数クラスがMyFunctionなら、静的メンバ関数を定義することができます: (const std :: vector&x、std :: vector &grad、void * data){ return(* reinterpret_cast (data))(x、grad); } ' –