3

请考虑以下代码:

public ref class Factory
{
public:
    generic <typename T> where T : value class, System::ValueType
    static System::Nullable<T> Create()
    {
        return System::Nullable<T>();
    }
};

Visual C++ 2008 吐出以下错误:

error C2440: 'return' : cannot convert from 'System::Nullable<T>' to 'System::Nullable<T>'

如果我用用户定义的类型替换“System::Nullable”类型,它就可以正常工作:

generic <typename T> where T : value class, System::ValueType
public value class MyType 
{ };

public ref class Factory
{
public:
    generic <typename T> where T : value class, System::ValueType
    static MyType<T> Create()
    {
        return MyType<T>();
    }
};

这是某种 VC++ 错误,还是我在这里遗漏了什么?

4

2 回答 2

1

对于那些可能遇到同样问题的人,您可以使用以下解决方法:

public ref class Factory
{
public:
    generic <typename T> where T : value class, System::ValueType
    static System::Nullable<T> Create()
    {
        return Workaround<T>::Nullable();
    }

private:
    generic <typename T> where T : System::ValueType, value class
    value struct Workaround {
        typedef System::Nullable<T> Nullable;
    };
};
于 2013-03-19T19:01:43.997 回答
0

你有没有尝试过:

public ref class Factory
{
public:
    generic <typename T> where T : value class, System::ValueType
    static System::Nullable<T> Create()
    {
        return Null;
    }
};
于 2012-07-26T20:25:16.357 回答