Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI: Returning Nullable<T> object from generic method

Please consider the following code:

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 spits out the following error:

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

If I replace the "System::Nullable" type by a user-defined type, it works just fine:

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>();
    }
};

Is this a VC++ bug of some kind, or am I missing something here?

like image 714
Sebacote Avatar asked Sep 05 '26 00:09

Sebacote


1 Answers

For those who might run into the same problem, you can use the following workaround:

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;
    };
};
like image 119
Sebacote Avatar answered Sep 08 '26 04:09

Sebacote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!