C++ 向函数发送任何类型的参数 [英] C++ send any type of argument to a function

查看:35
本文介绍了C++ 向函数发送任何类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事情是这样的:我想创建一个 void 函数,该函数将接收两个众所周知的值类型,另一个可以是任何类型的值.代码应该是这样的:

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;
    }
}

我试图使值的类型 const void* 但我收到一个错误(从 'const void*' 到 'short int' 的强制转换会丢失精度),因为我刚做了这个:short name = (short)value,这一定是一些疯狂的绝望尝试,希望能幸运.现在,我不知道是否有办法做到这一点,传递任何类型变量的指针,然后将其转换为实际值(我知道根据每种情况需要期望的变量类型.我该怎么做?谢谢!

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!

推荐答案

由于您似乎预先知道 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.

这篇关于C++ 向函数发送任何类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆