The class limit of a C ++ / CLI value will not compile. What for?

a few weeks ago, my colleague spent about two hours finding out why this piece of C ++ / CLI code would not compile with Visual Studio 2008 (I just tested it with Visual Studio 2010 ... the same story).

public ref class Test { generic<class T> where T : value class void MyMethod(Nullable<T> nullable) { } }; 

The compiler says: Error

1 error C3214: 'T': invalid argument type for general parameter 'T' generic 'System :: Nullable', did not meet the restriction 'System :: ValueType ^' C: \ Users \ Simon \ Desktop \ Projektdokumentation \ GridLayoutPanel \ Generics \ Generics.cpp 11 1 Generics

Adding ValueType will compile the code.

 public ref class Test { generic<class T> where T : value class, ValueType void MyMethod(Nullable<T> nullable) { } }; 

My question is now. What for? What is the difference between value class and ValueType ?

PS: see the Nullable definition for C ++: http://msdn.microsoft.com/de-de/library/b3h38hb0.aspx

+6
generics c ++ - cli
source share
2 answers

I analyzed the IL code for the following three methods:

 generic<class T> where T : value class, System::ValueType static void MyMethod(T arg) { } generic<typename T> where T: value class static void MyMethod2(T arg) { } generic<typename T> where T: ValueType static void MyMethod3(T arg) { } 

Relevant IL code that I parsed with .NET-Reflector:

 .method public hidebysig static void MyMethod<valuetype ([mscorlib]System.ValueType).ctor T> (!!T arg) cil managed { } .method public hidebysig static void MyMethod2<valuetype .ctor T>(!!T arg) cil managed { } .method public hidebysig static void MyMethod3<([mscorlib]System.ValueType) T>(!!T arg) cil managed { } 

This is the Nullable<T> IL declaration:

 .class public sequential ansi serializable sealed beforefieldinit Nullable<valuetype (System.ValueType) .ctor T> extends System.ValueType 

As you can clearly see, only the first restriction of the method corresponds to 100% with Nullable<T> . (The Btw: value class seems to imply a standard constructor). However, why the compiler creates different IL code for the (semantically) the same limitations remains a mystery. I will ask the Microsoft C ++ / CLI Guru for more information.

+5
source share

ValueType is a feature in that it is a β€œbase class” of value types, but not the value type itself. This is probably a problem.

A good list of the various objects that are used by the CLR can be found in this excellent blog post .

See also this and this thread for more information related to ValueType .

0
source share

All Articles