2017-07-12 10 views
-1
#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としてアクセスすると、プログラムは実行されません(ただし、苦情なしでコンパイルされます)。

この作品を作成するにはどうすればよいですか?

+0

'wrap'へのヌルポインタを渡さないようにすると効果がありますか? –

+3

なぜあなたは 'ClassFunction :: wrap(x、g、NULL)'を書いていましたか?なぜあなたはそれが働くことを期待していますか? – Angew

+0

最適化ライブラリ 'NLOPT'で提案されている定型コードと非常によく似ていますが、" ... 2行のヘルパー関数を使用しています。もしあなたの関数クラスがMyFunctionなら、静的メンバ関数を定義することができます: (const std :: vector &x、std :: vector &grad、void * data){ return(* reinterpret_cast (data))(x、grad); } ' –

答えて

1

は、以下を試してください

< reinterpret_castはClassFunction *>(データ)が適用されたときClassFunctionクラスのインスタンスへのデータポイント。

+0

はい、これは私が把握していなかったものです。ありがとう! –

関連する問題