12.4. Generic Classes in C++

Writing a generic class in C++ looks very much like a C# generic class. Still, as you look at the code in the following sample class, you'll notice that generic classes also have clear syntactic roots in the world of templates:

using namespace System;

generic <typename T, typename V>
ref class SampleClass {
public:
    T _param1;
    V _param2;

    SampleClass(T param1, V param2) {
        _param1 = param1;
        _param2 = param2;
    }

    T GetValue1() {
        return _param1;
    }

    V GetValue2() {
        return _param2;
    }

    void DisplayValues() {
        Console::WriteLine(L"Type Param1: {0}", _param1->ToString());
        Console::WriteLine(L"Type Param2: {0}", _param2->ToString());
    }
};

The first item that stands out here is the introduction of the generic keyword. This keyword identifies your class as being a managed, generic type. This keyword is followed by a set of type parameters enclosed in the already familiar angle brackets. This list of parameters is different than what you've seen with VB and C#. It includes the keyword typename, which is paired with the name for each type parameter. The keyword class can also be used interchangeably with typename in your parameter list.

The other syntax twist here is the ref keyword that precedes the class declaration. This ref keyword is not unique to a generic declaration. It is used to identify any reference managed type—generic or not. So, because your generic type here is a reference managed type, it required the addition of this qualifier.

Within the implementation ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.