c ++每个实例化对象具有特定功能的结构(或类)

时间:2012-08-09 08:22:11

标签: c++ callback function-pointers

我需要实现一个结构(或类),其中每个实例都有一个指向特定函数的“指针”。这可能吗?

这样的事情:

struct constrain{

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

评估“指向”特定函数的位置,这样当我创建约束对象时,我可以告诉对象方法评估哪个函数应该指向我以后使用它(例如我的约束对象将包含在std :: vector中)我可以调用特定的函数。

5 个答案:

答案 0 :(得分:2)

考虑使用std::function

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

最好通过引用传递vector作为pmr建议。以下是完整的示例:

#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::function,请考虑使用boost::function

答案 1 :(得分:0)

是的,这是可能的。您需要稍微更改一下定义:

struct constrain{

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

然而,这是一种C-ish方法。由于您使用的是c ++,因此可以使用函数对象(具有重载operator()的那些)。

答案 2 :(得分:0)

创建构造函数,其中一个参数是函数上的指针:

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

也在标题中更正:

double  (*evaluate) (vector <double> x_var);

答案 3 :(得分: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的使用情况。

如果您使用C ++ 11编译器,如果使用boost::functionboost::bind(或std::*等效项)可能会更简单:http://ideone.com/wF8Bz

答案 4 :(得分: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;
}

类似地,您可以使用结构成员指针作为指向函数的指针