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

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

问题描述

这里有云:我想创建将接收值的两个著名的类型,另一种可能是任何一个无效的功能。在code会是这样的:

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

我tryied使值的类型常量无效* ,但我得到一个错误(投从'常量无效*'到'短整型失去precision ),因为我只是做了这一点:短名称=(短)值,它必须是一些疯狂的不顾一切审讯,希望能幸运。现在,我不知道是否有这样做的方式,通过什么样的变量的指针,然后将其转换为它是什么(我知道变量的类型依赖于各种情况下的期望。
我会怎么做呢?谢谢!

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!

推荐答案

因为你似乎事先知道所有潜在类型的,并希望不同的行为因的类型,你可以只写了一系列函数重载:

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天全站免登陆