开发者

C++ howto use the same function twice with different name and different names for variables

I have a function that commands a device. This device is available twice so I need the same functionality for two devices. Out of maintenance reasons I don't want to have to code the function twice (one for each device) because then I always need to apply changes twice.

The functions are the same in principle but are supposed to work on different variables. Is it possible to instantiate this function with kind of a "varying" name, similar to template but not with classes but names? I try to provide an example. It should look something like this.

void function_x (int Var, double Vary, ...) {
int var3_x = getFunctionFromDatabase(var3_x);
double var2_x = getFunctionFromDatabase(var2_x);
// some operations
}

The functions are applied by two instances of a Device Handler class. The variables var1_x, var2_x and var3_x are stored in a data pool as var1_开发者_开发知识库1, var1_2, var2_1, ... the "same" variable but one for each device. One Controller commands the two devices via these variables and the data pool.

Is this possible somehow?

I hope that the problem got clear ;). This is my first question here :P. Thanks in advance for any help.


Why not use an array? E.g.

var1[0], var1[1], etc.

Use an array element for each device that you manage.

You could do some trickery with macros, but I think the code will be more clear if you use arrays.

Even if the variables are in a library that you can't change, you could set up arrays of pointers to the original variables in an initialization function. E.g.:

var1[0] = &var1_0;
var1[1] = &var1_1;

Then, function_x becomes function and would accept a parameter for the device index.


You say they have different variables, in which case it would be a simple case of overloading the function. Your example implies that you want to get the function from a database in which case you would need to use function pointers. Another option is that you have 1 function and you pass a handle (or some such) to it (as well as your arguments) to identify which device it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜