12.5. Generic Methods in C++

In C# and VB, every method that you write must appear within a type. Namespaces are not allowed to directly contain methods or fields. In C++, however, methods do not have this same constraint. So, the question is: Can these standalone methods be made generic within C++? And, of course, the answer is: Yes. This C++ feature certainly extends the flexibility of generic methods, because it may be preferable at times to have your generic methods exist entirely on their own. Consider the following examples:

generic <typename T>
T GenericMethod(T val) {
    Console::WriteLine(L"Value is: {0}", val->ToString());
    return val;
}

generic <typename T>
T GenericMethod(T paramVal, String^ stringVal) {
    Console::WriteLine(L"Param1 Value is: {0}", paramVal->ToString());
    Console::WriteLine(L"Param2 Value is: {0}", stringVal);
    return paramVal;
}

// fails at compile-time
generic <class U>
U GenericMethod(U val) {
    Console::WriteLine(L"Value is: {0}", val->ToString());
    return val;
}

These generic method declarations employ the same syntax constructs that you saw in the discussion of generic classes earlier. The method name is preceded by a declaration of the type parameter signature followed by the method that freely references any of the supplied type parameters.

In looking at these three methods, you'll notice that they are all overloaded representations of the GenericMethod() method. They are included here to simply reiterate some of the overloading concepts that are discussed ...

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.