c++ 具有每个实例化对象特定功能的结构(或类)
c++ A structure (or class) with specific function for each instanced object
>我需要实现一个结构(或类),其中每个实例都有一个指向特定函数的"指针"。这可能吗?
像这样:
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> ¶ms)
{
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::function
和 boost::bind
(如果使用带有 C++11 的编译器,则std::*
等效项)可能会简单得多:http://ideone.com/wF8Bz
相关文章:
- C++中用于结构的纯数组的类似于TableView/DataFrame的通用功能
- 对于没有功能的结构,"new (ptr) mystruct;"做什么?
- 在C 中,是否有树木数据结构具有相似的功能
- 如何使用结构内的功能指针调用私有函数
- C++要在其中添加接口功能的类层次结构
- 获得const结构和CIN的功能
- 访问嵌套结构的数据成员并将结构传递到功能C
- 在C 功能执行后,使用GCHANDLE CRALSES将大型结构从C#Unity脚本传递到C DLL
- 调用功能并将其设置为等于结构
- 在模板功能中打印任何结构
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 创建结构并传递IT功能
- 从公共功能原型中获取私有结构
- 在程序中传递功能具有结构C
- 局部结构通过使用共同的模板功能来影响不同的翻译单元
- 导入C 功能将结构的指针返回到VB.NET中
- 有关继承层次结构的问题,没有任何虚拟功能
- 如何从另一个功能中修改的结构的炭指针成员中获取值
- 操作员重新分配功能/结构返回什么
- 哪个功能结构更好