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

c++ A structure (or class) with specific function for each instanced object

本文关键字:功能 结构 或类 对象 实例化 c++      更新时间:2023-10-16

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

像这样:

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

其中求值"指向"特定函数,以便当我创建约束对象时,我可以告诉对象方法计算应该指向哪个函数,当我以后使用它时(例如,我的约束对象将包含在 std::vector 中)我可以调用特定函数。

考虑使用 std::function

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

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

#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

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

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

但是,这有点像C-ish方法。由于使用的是 c++,因此可以使用函数对象(具有重载operator()的对象)。

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

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

同样在标题中正确:

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

是的,我们确实有功能的指针创建这样的指针后,您可以使用函数的地址实例化它

void my_int_func(int x)
{
    printf( "%dn", x );
}
int main()
{
    void (*foo)(int); // this is a pointer to a function
    foo = &my_int_func;
    return 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;
};

请注意,这将没有任何指向调用它的"对象"的指针,因此您必须添加适当的参数(并且为了方便起见,可能对其进行了 typedef):

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::functionboost::bind(如果使用带有 C++11 的编译器,则std::*等效项)可能会简单得多:http://ideone.com/wF8Bz