C ++ sends any type of function argument

Here it is: I want to create a void function that receives two known types of values, and the other - anything. The code will look 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 tried to create a value type of 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 should be crazy desperate test, hoping that he was lucky. Now I don’t know if there is a way to do this, pass the pointer to any variable, and then convert it to what it is (I know what type of variable to expect depending on each case. How do I do this? Thanks!

+8
c ++ function types arguments void
source share
3 answers

Since you apparently know all potential value types in advance, and you need different behavior depending on the type, you can simply 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 temporary switch.

+7
source share

You must use patterns

 template <typename T> void change_settings(string element, short setting, T value); 
+12
source share

Assuming you are talking about switching at runtime (as opposed to compile time, in which case templates are probably the answer):

You can consider a variant class (for example, boost::variant ) or, possibly, use polymorphism (i.e., define an inheritance hierarchy and virtual functions to implement specific types of behavior).

+5
source share

All Articles