C++/CLI does support interface-based constraints on generics. An interface constraint basically allows you to specify that a given generic parameter type must implement a certain interface (or derive from a given base class), thus allowing you to call any methods (or access any properties) that are part of said interface.
In C++/CLI, you specify an interface constraint just after the closing > specifying the generic arguments, using the "where" keyword followed by the generic argument, a colon, and the interface it should implement. Here's an example that requires that argument T implements IEnumerable<V>:
#using <mscorlib.dll>
using namespace System;
using namespace System::Collections::Generic;
generic <typename T, typename V>
where T : IEnumerable<V>
ref class IWillEnumerateYou
{
public:
void DoIt(T t)
{
for each ( V v in t )
{
Console::WriteLine(v);
}
}
};
int main()
{
List<String^>^ stringList = gcnew List<String^>();
stringList->Add("String 1");
stringList->Add("String 2");
stringList->Add("String 3");
IWillEnumerateYou<List<String^>^, String^>^ en
= gcnew IWillEnumerateYou<List<String^>^, String^>();
en->DoIt(stringList);
}
.: tomasr | 2005-04-24 18:58:59 :.