gpt4 book ai didi

c# - 用于检索基础类型的空类

转载 作者:行者123 更新时间:2023-11-30 05:43:16 25 4
gpt4 key购买 nike

我想知道如何在 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# - 用于检索基础类型的空类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30296513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com