cpp函数检索各种数据类型的值

时间:2012-09-06 11:34:43

标签: c++ function types return-value

我想编写一个与此类似的cpp函数,其中outVal应该接受在每种情况下从相应函数返回的相应类型的数据。

void ReadFieldByType(char fieldType, string content, string& outStr, **unknown**& outVal){
unsigned int ifield;
char cField;
string sField;
double dField;
switch (fieldType)
                {
                case 'c':
                ReadChar(content, content, cField);
                outVal = cField;
                break;
                case 'd':
                ReadInteger(content, content, ifield);
                outVal = ifield;
                break;
                case 'f':
                ReadDouble(content, content, dField);
                outVal = dField;
                break;
                case 's':
                ReadString(content, content, sField);
                outVal = sField;
                break;
                default:
                break;
                }
                outStr = content;}

我不知道如何为outVal设置数据类型。这可以改进,还是有其他选择来完成这项任务?

3 个答案:

答案 0 :(得分:2)

看看boost::variant

在你的情况下,你会使用类似的东西:

typedef boost::variant<char, int double, std::string> out_t;

答案 1 :(得分:1)

您可以使用模板和typeid运算符来执行此操作:

template<class T>
void ReadField(string content, string& outStr, T& outVal)
{
    if (typeid(T) == typeid(int))
        ReadInteger(content, content, outVal);
    else if (typeid(T) == typeid(char))
        ReadChar(content, content, outVal);
    else if (typeid(T) == typeid(double))
        ReadDouble(content, content, outVal);
    else if (typeid(T) == typeid(std::string))
        ReadString(content, content, outVal);

    outStr = content;
}

虽然我不得不承认我不喜欢这个解决方案。

答案 2 :(得分:0)

使用union,它允许选择变量的类型;

union
{
    unsigned int ifield;
    char cField;
    string sField;
    double dField;} outVal;
void ReadFieldByType(char fieldType, string content, string& outStr, **unknown**& outVal){

switch (fieldType)
                {
                case 'c':
                ReadChar(content, content, cField);
                outVal.cField = cField;
                break;
                case 'd':
                ReadInteger(content, content, ifield);
                outVal.ifield = ifield;
                break;
                case 'f':
                ReadDouble(content, content, dField);
                outVal.dField = dField;
                break;
                case 's':
                ReadString(content, content, sField);
                outVal.sField = sField;
                break;
                default:
                break;
                }
                outStr = content;}