首页 > 解决方案 > 在单个函数 C++ 中返回不同的数据类型数据

问题描述

请找到以下代码。

template<typename T>
T GetValueFromDataType(Value &value)
{
    T jsonValue;
    if (value.IsString())
    {
        assert(value.IsString());
        jsonValue = value.GetString();      //here error is showing
        return jsonValue ;
    }
    else if (value.IsInt())
    {
        assert(value.IsInt());
        jsonValue = value.GetInt();
        return jsonValue;
    }
    else if (value.IsDouble())
    {
        assert(value.IsDouble());
        jsonValue= value.GetDouble();
        return jsonValue;
    }
    else if (value.IsBool())
    {
        assert(value.IsBool());
        jsonValue = value.GetBool();
        return jsonValue;
    }
}

jsonValue 在另一个函数中返回。在那里,我将返回变量声明为 int。理想情况下,它应该采用 int 大小写。但它给出了编译错误。

错误 C2440 '=':无法从 'const char *' 转换为 'int'

有没有办法使用上面的代码或任何其他构造

标签: c++jsonfunctiontemplatescompiler-errors

解决方案


如果您调用GetValueFromDataType<int>(...),则jsonValueinside 具有类型int并且jsonValue = value.GetString();没有任何意义。没关系,这value.IsString()是错误的,你有一个assert会失败的。如果代码在那里,它必须是有效的——除非你使用if constexpr. 的未采用分支if constexpr没有实例化,所以里面的代码只进行轻量级检查(就像在未实例化的模板中一样)。它不必是类型正确的。

坏的:

assert(value.IsString());
jsonValue = value.GetString();      // this line will be fully checked
                                    // regardless of the condition above

好的:

if constexpr (std::is_same_v<T, std::string>) {
   assert(value.IsString());        // make sure the value matches
   jsonValue = value.GetString();   // this line will NOT be fully checked 
                                    // if the condition in the if statement
                                    // (known at compile time) is false.
}

话虽如此,我不喜欢这种风格,如果可能的话,我更喜欢明确的专业化。

template<typename T>
T GetValueFromDataType(Value &value);

template <> 
std::string GetValueFromDataType<std::string>(Value &value) {
    assert(value.IsString());
    return value.GetString();
}
// etc

原因是它更加模块化。如果添加新类型,我们不必触及现有功能。


推荐阅读