1

各インスタンスが特定の関数への「ポインター」を持つ構造 (またはクラス) を実装する必要があります。これは可能ですか?

このようなもの:

struct constrain{

  string                              name;
  int                            direction;
  double evaluate (vector <double> &x_var);
};

評価特定の関数を「指す」ため、制約オブジェクトを作成するときに、オブジェクトメソッド評価が指す必要がある関数と後でそれをいつ使用するかを知ることができます(たとえば、制約オブジェクトは std:: 内に含まれます)。 vector) 特定の関数を呼び出すことができます。

4

5 に答える 5

2

使用を検討してくださいstd::function

struct Foo
{
    std::function<double (std::vector<double>)> func;
};

vectorpmrが提案したように、参照渡しする方が良いです。完全な例は次のとおりです。

#include <iostream>
#include <vector>
#include <functional>

struct Foo
{
    std::function<double (const std::vector<double> &)> func;
};

static double calc(const std::vector<double> &params)
{
    return 10.0;
}

int main()
{
    Foo f;
    f.func = calc;

    std::vector<double> v;
    std::cout << f.func(v) << std::endl;

    return 0;
}

実装で使用を検討してSTLいない場合std::functionboost::function

于 2012-08-09T08:28:53.587 に答える
0

引数の 1 つが関数へのポインターであるコンストラクターを作成します。

constraint::constraint (double (*pFn)(vector <double> x_var))
{
    this->evaluate = pFn
}

ヘッダーも正しい:

double  (*evaluate) (vector <double> x_var);
于 2012-08-09T08:26:28.470 に答える
0

はい、可能です。定義を少し変更する必要があります。

struct constrain{

  string                              name;
  int                            direction;
  double  (*evaluate)(vector <double> x_var);
};

ただし、これは少し C っぽいアプローチです。C++ を使用しているため、関数オブジェクト (オーバーロードされたものoperator()) を使用できます。

于 2012-08-09T08:26:01.680 に答える
0

関数またはファンクターへのポインターで可能です (たとえば、boost から)。

次のようなことを試してください:

struct constrain{
  string                              name;
  int                            direction;
  double  (*evaluate) (vector <double> &x_var);
};

また

struct constrain{
  string                              name;
  int                            direction;
  boost::function<double(vector &<double>)> evaluate;
};

これには、呼び出し元の「オブジェクト」へのポインターがないことに注意してください。そのため、適切なパラメーターを追加する必要があります (おそらく便宜上、型定義します)。

struct constrain{
  typedef double  (*callback_t) (constrain *obj, vector <double> &x_var);
  string                              name;
  int                            direction;
  callback_t evaluate_f;

  // helper function
  double evaluate(vector <double> &x_var) {
    return evaluate_f(this, x_var);
  }
};

使用方法については、 http://ideone.com/VlAvDを確認してください。

boost::functionand boost::bind(またはstd::*C++11 でコンパイラを使用している場合は同等のもの) を使用すると、はるかに簡単になる可能性があります: http://ideone.com/wF8Bz

于 2012-08-09T08:28:19.410 に答える
0

はい、関数へのポインタがあります。このようなポインタを作成したら、関数のアドレスでインスタンス化できます。

void my_int_func(int x)
{
    printf( "%d\n", x );
}

int main()
{
    void (*foo)(int); // this is a pointer to a function
    foo = &my_int_func;

    return 0;
}

同様に、構造体メンバー ポインターを関数へのポインターとして使用できます。

于 2012-08-09T08:29:13.683 に答える