mardi 28 juillet 2015

Generalize a function call for a collection of functions with differing number/type of parameters?

I understand that the title is a bit of a mouthful, but sometimes a question is not only hard to answer but also hard to ask. Let me try to explain with examples. I'm not sure if this is a tough problem, or if I just don't know enough to answer it quickly. Here we go.

Consider that I have a collection of functions. I'll write out three sample ones:

double foo();
void bar(int q);
std::string vex(double p, int d);

I want to write code so that I can call any three of these functions, given the name of the function and its arguments by user decision. So let's assume there's an input like:

>bar [4]

How can I write code that takes this input and calls the respective function, while still being general enough to handle any other input, such as:

>foo []
>vex [5.2, 3.923]

At the moment, I am considering the idea of rewriting my collection of functions to take a vector of std::string arguments, and have function specific code to convert these elements:

void pisces(std::vector<std::string> args){ //params: int g, double f,   
                                            //std::string p
    /* Handle the params */
    int g = std::stoi(args[0]);
    double f = std::stod(args[1]);
    std::string p = args[2];

    /* do work with them here */
}

However this seems kind of like a cheat and I want to use a more generalized and eloquent solution if there is one.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire