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!
You should use templates
template <typename T>
void change_settings(string element, short setting, T value);
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With