Generics in Managed Extensions for C++

By now, many people are aware that one of the new features in C# 2.0 is generic types (generics for short). But some may not be aware that generics is actually part of the CLR which means that any .NET language can take advantage of generics. In fact, both VB and Managed Extensions for C++ allow you to consume as well as create generic types.

 

In this example, I'm going to show you how to implement a Stack as a generic type in Managed Extensions for C++. Below is a declaration of the Stack type. If you haven't seen the new Managed Extesions for C++ features, some of the code may be new to you.

 

generic<typename T>

public ref class Stack

{

private:

     array<T> ^ m_items;

     unsigned int m_count;

 

public:

     Stack() { m_items = gcnew array<T>(STACK_SIZE); }

     void Push(T item) { m_items[m_count++] = item; }

     T Pop() { if (m_count > 0) return m_items[--m_count]; }

};

 

The first thing to notice is the generic keyword followed by the type parameter T. The syntax for generics in C++ is quite similar to C++ templates. The next thing to note is the ref keyword which indicates that this is a reference type as opposed to a value type (this is equivalent to the __gc keyword in version 1.0/1.1 of Managed Extensions for C++). Also, in the new version of the Managed Extensions for C++, arrays are declared a bit differently, using the stdcli::language::array<> type. Once you have declared a managed array however, you can use the familiar [] to index into it.

 

There's also the new ^ symbol which indicates that a variable is a handle to an object on the managed heap, i.e. a managed pointer (this is equivalent to the __gc* keyword in version 1.0/1.1 of Managed Extensions for C++)). Finally, there's the gcnew keyword that allows you to instantiate an object on the managed heap (in version 1.0/1.1 of Managed Extensions for C++, you could use the new keyword for instantiating both native and managed types).

 

To wrap up, here's a code snippet that shows how to use our Stack class. The code is self explanatory, so I'm not going to describe it in detail.

 

void main()

{

     // A stack of integers

     Stack<int> ^ s = gcnew Stack<int>();

     for (int i = 0; i < STACK_SIZE; i++) s->Push(i);

     for (int i = 0; i < STACK_SIZE; i++) Console::Write("{0} ", s->Pop());

     Console::WriteLine();

 

     // A stack of strings

     Stack<String ^> ^ s2 = gcnew Stack<String ^>();

     s2->Push("One");

     s2->Push("Two");

     s2->Push("Three");

     Console::WriteLine("{0} {1} {2}", s2->Pop(), s2->Pop(), s2->Pop());

}

posted on 2004-08-02 09:16  LeighSword  阅读(247)  评论(2编辑  收藏  举报

导航