Introduction
Beginning with .NET 2.0, Microsoft has introduced generics into the CLI whereby parameterized types can be declared and used. For C# and VB users, this must have been extremely exciting news; but for C++ people who were already used to templates, this might not have sounded all that interesting. You often hear C++ people ask why they need to use generics when they already have templates. [Note - In C++/CLI, templates can be used both with native and with managed types].
Generics and templates, while similar in nature, are also different in many ways. The most outstanding of these differences is that while templates are implemented by the compiler, generics are instantiated at runtime by the CLR's execution engine (this is possible because generics is directly supported by MSIL). For a detailed write-up on how templates and generics differ, see Brandon Bray's blog entry - Templates and Generics.
This article is not intended to demonstrate how generics are cooler than templates (or even the reverse for that matter), rather it just tries to expose the syntactic usage of generics in C++/CLI. I would like to state here that I found generics rather limited when compared to templates, that too despite not being a core-template guy myself.
Basic syntax
Throughout the article, I'll show some code using templates and then show the equivalent code using generics. Here's a typical native class template.
template<typename T1, typename T2> class NativeData
{
public:
NativeData(T1 t1)
{
m_t1 = t1;
}
void DoStuff(T2 t2)
{
}
private:
T1 m_t1;
};
Now, here's the equivalent in generics :-
generic<typename T1, typename T2> ref class GenericData
{
public:
GenericData(T1 t1)
{
m_t1 = t1;
}
void DoStuff(T2 t2)
{
}
private:
T1 m_t1;
};
Looks just about identical, except that instead of template
, the keyword to be used is generic
. [Note - generic
is one of the 3 new keywords introduced in C++/CLI, the other two being gcnew
and nullptr
. All other keywords are context sensitive keywords like ref
or spaced keywords like for each
].
Constraints
See the following template-based class :-
template<typename T> class Native
{
public:
void Start(int x)
{
T* t = new T();
t->Bark(x);
t->WagTail();
delete t;
}
};
Since templates use lazy constraints, the above code compiles fine (the compiler won't specialize the class template until an instantiation).
And assuming we want to use the class as follows :-
Native<NativeDog> d1;
d1.Start(100);
We need to have a class NativeDog
similar to :-
class NativeDog
{
public:
void Bark(int Loudness)
{
Console::WriteLine("NativeDog::Bark {0}",Loudness);
}
void WagTail()
{
Console::WriteLine("NativeDog::WagTail");
}
};
As long as the class we are specifying as the template type parameter has the Bark
and WagTail
methods, it compiles fine. But in generics, we have to specify the constraint (since generics are implemented at runtime). The generic equivalent will be :-
interface class IDog
{
void Bark(int Loudness);
void WagTail();
};
generic<typename T> where T:IDog ref class GenRef
{
public:
void Start(int x)
{
T t = Activator::CreateInstance<T>();
t->Bark(x);
t->WagTail();
delete safe_cast<Object^>(t);
}
};
Now that we have specified a constraint for the generic parameter, we can invoke methods on it (as allowed by the constraint). If you are wondering why I had to use the generic overload of Activator::CreateInstance
, it's because the compiler won't allow you to gcnew
a generic parameter. Similarly, it won't let you delete
a generic parameter and hence the safe_cast
to Object
.
To use the class, we do something like :-
ref class Dog : IDog
{
public:
void Bark(int Loudness)
{
Console::WriteLine("Dog::Bark {0}",Loudness);
}
void WagTail()
{
Console::WriteLine("Dog::WagTail");
}
};
GenRef<Dog^> g1;
g1.Start(100);
Generic functions
C++/CLI also supports generic functions (you can have a non-generic class with a generic function or you can have a global generic function). For example :-
generic<typename T> where T:IDog void DoAll(T t)
{
t->Bark(0);
t->WagTail();
}
Issues with the constraint mechanism
Doing some things are rather more complicated with generics than with templates.
Example 1
See the following template code :
template<typename T> void NativeIncrement(T t, int x)
{
t += x;
}
Now, the basic issue with doing this with generics would be that it's difficult to define a constraint that will allow the +=
operator to work on the generic type parameter. One possible workaround is to define an interface called IIncrementable
(similar to the generic collection classes using generic interfaces like IComparable<T>
)
interface class IIncrementable
{
void Add(int);
};
generic<typename T> where T:IIncrementable void RefIncrement(T t, int x)
{
t->Add(x);
}
And we can use it on classes that implement IIncrementable
:-
ref class MyInt : IIncrementable
{
public:
MyInt(int n) : m_num(n){}
void Add(int x)
{
m_num += x;
}
private:
int m_num;
};
We still cannot use the generic function RefIncrement
with simple types like int
, float
etc. For that, we can use a work-around suggested by Jambo (discussed later in this article).
Example 2
See the following function template :-
template<typename T> T NativeAdd(T t1, T t2)
{
return t1 + t2;
}
As above, since there is no .NET interface called IAddable
, we have to work around the situation. Instead of using an interface like we did last time, we'll use a ref
class as constraint - so we can define a CLI-compatible binary +
operator.
ref class A1
{
public:
A1(int x):m_x(x){}
static A1^ operator +(const A1^ a1,const A1^ a2)
{
return gcnew A1(a1->m_x + a2->m_x);
}
int m_x;
};
generic<typename T> where T:A1 T GenericAdd(T t1, T t2)
{
A1^ tmp = gcnew A1(t1->m_x + t2->m_x);
return static_cast<T>(tmp);
}
And yeah, all that ugly casting is necessary. Again this generic function will not work on simple types like int
, float
etc.
Work-around for simple types
Jambo calls this the Adapter Pattern [but neither of us are really sure whether that's what this should be called]. Basically we have a singleton class, NumericalAdapter
and a generic interface, INumericalOperations
with Add
and Subtract
methods. The NumericalAdapter
class has inner classes, one for each type like IntNumericalAdapter
, FloatNumericalAdapter
etc. and also provides a static generic method GetNumericalAdapter
which returns a INumericalOperations<T>
object.
generic<typename T> interface class INumericalOperations
{
T Add( T t1, T t2 );
T Subtract( T t1, T t2 );
};
ref class NumericalAdapter
{
private:
static NumericalAdapter^ m_NumericalAdapter;
NumericalAdapter(){};
public:
static NumericalAdapter()
{
m_NumericalAdapter = gcnew NumericalAdapter();
}
private:
ref class IntNumericalAdapter : INumericalOperations<int>
{
public:
int Add( int t1, int t2 )
{
return t1 + t2;
}
int Subtract ( int t1, int t2 )
{
return t1 - t2;
}
};
ref class FloatNumericalAdapter : INumericalOperations<float>
{
public:
float Add( float t1, float t2 )
{
return t1 + t2;
}
float Subtract ( float t1, float t2 )
{
return t1 - t2;
}
};
public:
generic<typename T> static INumericalOperations<T>^ GetNumericalAdapter()
{
Type^ typ = T::typeid;
if( typ == int::typeid)
{
return dynamic_cast<INumericalOperations<T>^>(gcnew IntNumericalAdapter());
}
if( typ == float::typeid)
{
return dynamic_cast<INumericalOperations<T>^>(gcnew FloatNumericalAdapter());
}
return nullptr;
}
};
And we use the class as follows :-
int i1 = 7, i2 = 23;
int i3 = NumericalAdapter::GetNumericalAdapter<int>()->Add(i1, i2);
float f1 = 5.67f, f2 = 7.13f;
float f3 = NumericalAdapter::GetNumericalAdapter<float>()->Add(f1, f2);
Pretty cool, huh? They don't call Jambo Mister DotNet for nothing.
Conclusion
Generics are not as powerful or flexible as templates are (the intentions behind generics were probably different from that for templates), but if you want your code to be compatible with other CLI languages like C# or VB.NET, you'd be much better off using generics instead of templates wherever possible. Generics can also be used to write generic wrappers over existing C++ template libraries so as to expose them to the rest of the .NET world. As usual, please feel free to submit your criticisms, suggestions and other feedback.