C++ send any type of argument to a function

╄→гoц情女王★ 提交于 2019-12-04 03:11:25

问题


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!


回答1:


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.




回答2:


You should use templates

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



回答3:


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).



来源:https://stackoverflow.com/questions/14175914/c-send-any-type-of-argument-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!