Null类来检索基础类型

Null class to retrieve the underlying type

本文关键字:类型 检索 Null      更新时间:2023-10-16

我想知道如何在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...

这样,你可以在模板中使用函数,模板将自己解析正确的调用。