Error Compiling a Generic Function with a Constraint  
Author Message
ChrisPD





PostPosted: Visual C++ Language, Error Compiling a Generic Function with a Constraint Top

I'm trying to return a nullptr from a generic function in C++/CLI and I am receiving the following error:

error C2440: 'return' : cannot convert from 'nullptr' to 'T'

'T' may be a value type at runtime: consider using 'T()' instead

I wrote the following C# and C++ classes to test the difference. The code compiled and ran in C# but the code will not compile in C++/CLI. Here’s the C# code:

using System;

using System.Collections.Generic;

using System.Text;

namespace TestGenerics

{

class Program

{

static void Main( string[] args )

{

Something st = new Something();

string s = st.DoSomething<string>();

Console.WriteLine( "s = " + (s == null "null" : s ));

Console.ReadKey();

}

}

public class Something

{

public T DoSomething<T>() where T : class

{

return null;

}

}

}

Here’s the C++/CLI code:

using namespace System;

namespace CPPSomething {

public ref class Something

{

public:

generic <class T> where T : ref class

T DoSomething()

{

return nullptr;

}

};

}

So, my question is, do I have the wrong syntax in C++/CLI, is this not possible in C++/CLI, or is this a compiler bug which prevents recognizing our constraint



Visual C++12  
 
 
Mike Danes





PostPosted: Visual C++ Language, Error Compiling a Generic Function with a Constraint Top

There is a thread about something like this, see

http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=881717&SiteID=1

The solution is simple: use T() instead of nullptr as the error message says.

It looks like a compiler bug to me, the example quoted from C++/CLI spec in the above thread does not compile.

In addition the text is pretty clear:

"The literal nullptr cannot be converted to a type given by a generic type parameter, except if the type

parameter is known to be a handle type"