The generic type of C ++ is based on the template technology. The template itself is not an independent compilation unit, but is bound to the actual parameter type during compilation for template instantiation. Similar to the macro development of C language, there is no independent template type at runtime. The template's constraints on generic parameters are based on the syntax features of the operation. It is a static duck typing mechanism and is very flexible.
The following code defines a generic Add function. It only requires + operations for the generic parameter T, does not require T to be a subclass of a class, or implements an interface. Int, double, std: string, and Other types supporting the + operator can be successfully matched with T.
// C ++
Template <typename T>
T Add (const T & t1, const T & t2 ){
Return t1 + t2;
}
Int main (){
Int I = Add (1, 2 );
Double d = Add (1.1, 2.2 );
Std: string s = Add (std: string ("abc"), std: string ("def "));
Std: cout <I <"" <d <"" <s <std: endl;
Return 0;
}
Output:
> 3 3.3 abcdef
Similar Code cannot be compiled in C:
This is because C # adopts the reification-based generic mechanism, and generic classes are compiled separately and exist at runtime. Therefore, C # has stricter requirements on generic parameters, you can only use the where keyword to express the constraints based on the inheritance relationship, and cannot use the duck typing method to express the type constraints. Compared with templates, this mechanism provides better support for reflection and metaprogramming, but its disadvantage is that generic expressions are inferior to templates. Fortunately, the dynamic type mechanism is introduced in C #4.0. We can use dynamic types to implement the wildcard parameter Constraints Based on duck typing.
// C #
Static class Calculator {
Public static T Add <T> (T t1, T t2 ){
Dynamic d1 = t1;
Dynamic d2 = t2;
Return (T) (d1 + d2 );
}
}
Public static void Main (string [] args ){
Int I = Calculator. Add (1, 2 );
Double d = Calculator. Add (1.1, 2.2 );
String s = Calculator. Add ("abc", "def ");
Console. WriteLine (I + "" + d + "" + s );
}
Output:
> 3 3.3 abcdef
In addition to operator overloading, this method is also applicable to common method calls. This method is a dynamic duck typing generic parameter constraint mechanism that relies on runtime method lookup, which is different from the checking during template compilation, it requires the user to ensure that the input object meets the corresponding requirements.
Refer:
Wikipedia: Generic Programming
Dynamic Objects in C #4.0
Where (generic type constraint) (C # Reference)