C ++ / CLI:从泛型方法</t>返回Nullable <t>对象

时间:2012-07-26 20:22:20

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

请考虑以下代码:

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 ++错误,还是我在这里遗漏了什么?

2 个答案:

答案 0 :(得分: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;
    };
};

答案 1 :(得分:0)

你试过了吗?

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