c++ - 在单个函数 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'
有没有办法使用上面的代码或任何其他构造
解决方案
如果您调用GetValueFromDataType<int>(...)
,则jsonValue
inside 具有类型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
原因是它更加模块化。如果添加新类型,我们不必触及现有功能。
推荐阅读
- mongodb - MongoDB Group BY 中缺少标题
- javascript - Highcharts:使用数组作为数据系列 - 排序
- scala - Databricks - 无法从 DataFrame 写入 Delta 位置
- c# - 如何覆盖委托参数?
- javascript - 如何使用 php 和 symfony 4 获取两个日期之间的差异?
- windows - ffmpeg - 报告文件级别无效(Windows)
- google-cloud-platform - 在 Cloud Endpoints 后面隐藏 Cloud Functions 执行
- python - 日志记录在本地工作,但不在远程
- javascript - 如何根据 JavaScript 中的二进制表示对整数数组进行排序?
- javascript - 从类加载方法(图像/音频)中返回一个值