Null类来检索基础类型
Null class to retrieve the underlying type
我想知道如何在c++中编写以下c#代码
object data;
private T GetJsonData<T>(String node)
{
Type type=typeof(T);
Type nType=Nullable.GetUnderlyingType(type);
if(null!=nType)
{
if(node=="")
return default(T);
return (T)Convert.ChangeType(data,nType);
}
}
我认为std
名称空间应该有一些类似的方法可以做同样的事情,但我找不到一个例子来做上面的事情。
我认为给定的代码不能直接转换为c++,因为既没有中央转换类,也无法检查类型是否可以具有nullptr值。当然,你可以使用类型特征等机制自行构建这两种行为:
http://www.cplusplus.com/reference/type_traits/你可以用函数重载自己构建一个nullptr检查器:
inline bool canbeNULL(bool){return false;}
inline bool canbeNULL(int *){return true;}
// and all others...
上面的代码看起来像:
T dummy;
if(canbeNULL(dummy))
{
// do what you have to do
}
还可以使用方法重载将不同的会话函数包装到自己的Convert
类中。
在您的示例中,您使用一个函数将JSON转换为c++对象。因为JSON只有几种不同的类型,我会用函数重载来解决你的问题。由于函数重载不能处理返回类型,因此必须将返回类型作为参数,如:
void GetJsonData(std::string strin, bool &returnvalue) {do the stuff}
void GetJsonData(std::string strin, int &returnvalue) {do the stuff}
void GetJsonData(std::string strin, double &returnvalue) {do the stuff}
// and more...
这样,你可以在模板中使用函数,模板将自己解析正确的调用。
相关文章:
- 如何在 C++17 中检索 std::filesystem::file_time_type 的时钟类型
- 如何从C 中的集合中检索多个继承类型
- 检索不同类型的对象指针
- 自动检索返回类型的模板功能
- 从保存变量数据类型的数据结构中检索值,而不指定返回类型
- 为什么C++模板类型匹配不检索引用限定符"&"?
- 使用友元函数从多态类中检索类型信息
- 从未知dll(c++)中检索函数(名称、返回类型、参数)
- 如何检索要在模板中使用的函数的返回类型
- 如何从概念中检索类型?
- cpp函数来检索各种数据类型的值
- 从数据库中以 blob 数据类型形式存储的原始图像数据中检索 CImage 对象
- std::用户定义类型的映射在检索值时会使程序崩溃
- 在编译时检索 Opencv Mat_的类型<T>
- ArgumentError 在 Boost.Python 中的类中存储和检索指针:错误的类型
- 根据对象的类型从矢量中检索对象
- 从 std::type_info 检索数据类型的大小
- 从 c++ 检索 Python 类型
- 按类型检索可变类的给定成员
- 根据所包含的类型检索向量的向量