将函数指针保存并加载到文件 [英] Save and load function pointers to file

查看:123
本文介绍了将函数指针保存并加载到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

typedef float (*MathsOperation)(float _1, float _2);
struct Data
{
    float x, y;
    MathsOperation op; 
};
Data data[100];

float Add(float _1, float _2){//add}
float Sub(float _1, float _2){//subtract}
float Mul(float _1, float _2){//multiply}
// other maths operations

for (int i = 0; i < 100; ++i)
{
    // assign one of the maths operators above to data struct member op
    // according to some condition (maybe some user input):
    if(condition1) data[i].op = &Add;
    if(condition2) data[i].op = &Sub;
    if(condition3) data[i].op = &Mul;
    // etc.
}

现在,我想以某种方式将data数组保存到文件中并稍后加载(也许在另一个程序中,该程序不知道用于将运算符分配给每个数组元素的条件).显然,每次我运行该应用程序时,指针都会有所不同.所以,我的问题是做到这一点的最佳方法是什么?

Now I'd like to somehow save the dataarray to a file and load it later (maybe in another program which doesn't know about the conditions that were used to assign the operators to each array element). Obviously, the pointers would be different every time I ran the application. So, my question is what is the best way to do this?

推荐答案

无论如何,您都不能将函数"存储为数据,并且正如您所说的那样,将指针存储在外部媒体中是行不通的.因此,在这种情况下,您要做的就是存储一个运算符值,例如

You can't store "functions" as data anyway, and as you say, storing pointers in external media doesn't work. So, what you have to do in this case is store an operator value, e.g.

enum Operator
{ 
   Op_Add,
   Op_Sub,
   Op_Mul,
   Op_Largest    // For array size below.
};

而不是:

if(condition1) data[i].op = &Add;
if(condition2) data[i].op = &Sub;
if(condition3) data[i].op = &Mul;

拥有:

if(condition1) data[i].op = Op_Add;
if(condition2) data[i].op = Op_Sub;
if(condition3) data[i].op = Op_Mul;

由于它是整数类型值,因此可以将其存储在文件中,然后可以执行以下操作:

Since that is an integer type value, it can be stored in a file, and you can then do:

// Or `fin.read(reinterpret_cast<char*>(data), sizeof(data))
fin >> op >> x >> y; 

if (op == Op_Add) ... 
else if (op == Op_Sub) ... 

或者具有一个用op编制索引的函数指针数组.换句话说:

Or have a function pointer array that you index with op... In other words:

typedef float (*MathsOperation)(float _1, float _2);
...

MathsOperation mathsOps[Op_Largest] = { &Add, &Sub, &Mul };

...
mathsOps[op](x, y);
...

这篇关于将函数指针保存并加载到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆