Click here to Skip to main content
Click here to Skip to main content
Go to top

Using generics in C++/CLI

, , 7 Dec 2004
Rate this:
Please Sign up or sign in to vote.
Introduces generics and compares it with templates

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Authors

James T. Johnson
Software Developer (Senior) InfoPlanIT, LLC
United States United States
James has been programming in C/C++ since 1998, and grew fond of databases in 1999. His latest interest has been in C# and .NET where he has been having fun writing code starting when .NET v1.0 was in its first beta.
 
He is currently a senior developer and consultant for InfoPlanIT, a small international consulting company that focuses on custom solutions and business intelligence applications.
 
He was previously employed by ComponentOne where he was a Product Manager for the ActiveReports, Data Dynamics Reports, and ActiveAnalysis products.
 
Code contained in articles where he is the sole author is licensed via the new BSD license.
Follow on   LinkedIn

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
QuestionHow to use generic list find method in C++/CLI PinmemberAYDIN EBRAHIMI HOMAY28-Jul-13 21:09 
GeneralNoob Troubles PinmemberDraken Nuwar14-Oct-06 8:00 
GeneralRe: Noob Troubles PinmemberBartosz Bien4-Feb-07 21:01 
GeneralNice Article PinmemberHolger Grund1-Feb-05 5:37 
GeneralC++ developers choose PinmemberMajid Shahabfar8-Dec-04 23:07 
GeneralRe: C++ developers choose PinsussArno Nimoy9-Dec-04 10:31 
GeneralRe: C++ developers choose PinmemberNemanja Trifunovic10-Dec-04 9:46 
GeneralRe: C++ developers choose PinmemberNemanja Trifunovic10-Dec-04 9:37 
QuestionSurely that's not all?? PinmemberDon Clugston8-Dec-04 18:26 
AnswerRe: Surely that's not all?? PinstaffNishant S8-Dec-04 18:37 
Don Clugston wrote:
I notice also that Dog is defined as
ref class Dog: IDog
Does this mean that to use a generic, you have to specify the interfaces that it supports when you declare the class?

 
Generics use the subtype constraint mechanism for type parameters. This is because, unlike templates, generics is implemented by the CLR's execution engine at run-time rather than at compile-time.
 
So to be able to invoke methods/properties on a type parameter you need to specify a constraint (and I chose to use an interface as constraint rather than use an abstract class).
 
Don Clugston wrote:
It seems that most of the things you've shown here could be done with ordinary functions that accept an IDog *.
 
The examples were trivial code snippets used to show the generic syntax in C++/CLI and not a proper exposition for what you can do with generics. There are a few C# based articles on CP and MSDN that explain what generics brings into the CLI.
 
Don Clugston wrote:
Surely that's not all. They must be good for something?
 
As far as I could make out, if you don't intend to interop with other languages, you'd be okay sticking with templates in C++ (since templates now also work on managed types). But then that's merely my opinion.
 
Quoting Brandon Bray :-
 
Certainly, there will be evangelists for either option. The best option for C++ is to support both mechanisms. Having both templates and generics satisfies anyone who believes one is better than the other. Of course, any pragmatic programmer will realize that having both gives the programmer the ability to use the right feature to solve the problem at hand. Both generics and templates have shortcomings, but using both features together actually yields an even more expressive language.
 
A very compelling scenario is using templates to create highly efficient data structures, but exposing that type at the assembly boundary through a generic interface. This is similar to a factory pattern that uses private types that inherit from public interfaces. Using this pattern, a specialized C++ collection class can take advantage of frameworks APIs that use the interface and allows other languages to make use of the type through the interface

 

My blog on C++/CLI, MFC/Win32, .NET - void Nish(char* szBlog);
My MVP tips, tricks and essays web site - www.voidnish.com

Generalsecond example PinmemberGoran Mitrovic7-Dec-04 21:25 
GeneralRe: second example PinstaffNishant S7-Dec-04 21:34 
GeneralRe: second example PinmemberHolger Grund1-Feb-05 5:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 8 Dec 2004
Article Copyright 2004 by James T. Johnson, Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid