【问题标题】:How to determine in C++ typeof of template<class T> for deserialize data?如何在 C++ 中确定模板<class T> 的类型以反序列化数据?
【发布时间】:2012-02-29 18:20:08
【问题描述】:

问题:

How to determine typeof of **managed** template<class T> for deserialize data?
In C# a method to do this is typeof(T) but in C++ is ... ?

感谢您的合作。

行:

DataContractSerializer^ serializer = gcnew DataContractSerialize(typeof(T));

错误信息

错误 1 ​​错误 C2275: 'T' : 非法使用此类型作为表达式 c:...\SerializationExtensions.h 33 1 iOffshoreSteadyStateEngine

错误 2 错误 C3861: 'typeof': 找不到标识符 c:...\SerializationExtensions.h 33 1 iOffshoreSteadyStateEngine

代码:

template<class T>
T SerializationExtensions<T>::Deserialize(System::String^ serialized)
{
    DataContractSerializer^ serializer = gcnew DataContractSerialize(typeof(T));
    StringReader^ reader = gcnew StringReader(serialized);
    XmlTextReader^ stm = gcnew XmlTextReader(reader);
    return (T)serializer->ReadObject(stm);
}

【问题讨论】:

    标签: .net visual-studio-2010 c++-cli


    【解决方案1】:

    相当于 C# 的 typeof(T) 将是 T::typeid。当然,这适用于任何类型,而不仅仅是泛型类型,因此您也可以这样做:System::String::typeid

    另外,您确定要使用template&lt;class T&gt; 而不是generic&lt;class T&gt;?您可以阅读它们之间的差异at this blog post。一个区别是模板是在编译时创建的,而泛型是在运行时创建的。正因为如此,模板在泛型所在的地方不是跨语言兼容的。该博客文章中有一个完整的列表,如果您不确定,我建议您阅读它。

    Here's the documentation on MSDN for typeid.

    【讨论】:

    • 克里斯托弗,你中了目标。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-17
    • 2019-07-30
    • 2020-03-02
    • 1970-01-01
    • 2023-03-30
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多