Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ send any type of argument to a function

Here it goes: I want to create a void function that will receive two well-known type of values and another one that could be anything. The code would be like this:

void change_settings(string element, short setting, ??? value) {
    switch (setting) {
        case ST_NAME:
            // Cast value to string or char* and change element.name
        break;
        case ST_AMOUNT:
            // Cast value to integer and change element.amount
        break;
        case ST_ENABLED:
            // Cast value to boolean and change element.enabled
        break;
    }
}

I tryied to make the value's type const void* but I get an error (cast from ‘const void*’ to ‘short int’ loses precision) because I just did this: short name = (short)value, which must be some crazy desperate trial, hoping to get lucky. Now, I don't know if there's a way of doing this, pass the pointer of whatever kind of variable then convert it to what it is (I know the type of variable to expect depending on each case. How would I do this? Thanks!

like image 857
ali Avatar asked Jan 05 '13 20:01

ali


3 Answers

You should use templates

template <typename T>
void change_settings(string element, short setting, T value);
like image 82
Caesar Avatar answered Oct 13 '22 00:10

Caesar


Since you seem to know in advance all the potential types of value, and you want different behavior depending on the type, you can just write a series of function overloads:

void change_settings(const std::string& element, short setting, const std::string& value);

void change_settings(const std::string& element, short setting, int value);

void change_settings(const std::string& element, short setting, bool value);

This eliminates the need for a run-time switch.

like image 24
Charles Salvia Avatar answered Oct 13 '22 01:10

Charles Salvia


Assuming you're talking about run-time switching (as opposed to compile-time, in which case templates are probably the answer):

You could consider a variant class (e.g. boost::variant), or perhaps use polymorphism (i.e. define an inheritance hierarchy, and virtual functions to implement the specific behaviours).

like image 25
Oliver Charlesworth Avatar answered Oct 12 '22 23:10

Oliver Charlesworth