简体   繁体   中英

array of overloaded functions in c++

I have several overloaded functions in c++ and I would like to make an array of them, so that I can use them in a loop (in fact I want to call them randomly). Could you help ? Tutorials only show how to do arrays of function pointers with identical function arguments.

I think that the main problem here is that it seems that what you want requires the determination of the type and order of the function arguments in execution time and not in compilation time. What is your main goal here? execution speed? code readability or "correctness"? If you go for execution speed, then I think that there is some ugly solution. As far I understand your problem, you will decide which "overloaded function" you will call using a random choice of the index of the array. So one not necessarily safe possibility is to use functors and pass to the creator of each functor in the array pointers to the variables it will use in the future as if those variables are its arguments. But this works only if you allways will use the same variables as the arguments of the "function" calls.

Wait so you want to call a set of overloaded functions randomly?

Why not just make a quick rand function and then use a switch statement?

for example, lets say you have 3 overloaded functions:

srand(time(0));
int rand = rand() % 3 // Replace 3 with number of functions.

switch(rand)
{
   case 0:
      test("this is a string!");
      break;
   case 1:
      test(12, 16);
      break;
   case 2:
      test(16.2, 3, "Hello, World!");
      break;
}

Otherwise you will most likely have troubles due to the fact that each function in the array would be different and expect different parameters. You would need some way to determine what parameters go to which function of which you cannot do with just the address of the function.

I would say it is rather impossible to accomplish what you are trying to do unless you use a method similar to the one described above, and even then you would need to get the parameters from somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM