Now, in your client code, the example creates two separate instances of this inner class. Once you've cre-
ated these two instances, you proceed to call the
IncrementCounter()
method which, in turn, increments
a static data member. Because this data member is static, you would think that it will be incremented to
a value of 3 after a third and final call to
IncrementCounter()
. Because these inner classes are both
instances of
ClassI<int>
, it would seem logical for them to share this static member. However, because
each of these instances has a different type argument for its outer class, the two instances are considered
unique and separate.
Methods in Generic Classes
A C++ generic class imposes no specific constraints on its methods. Any method that could be included
in a non-generic class can also be included in a generic class. As with the other .NET languages that sup-
port generics, you are free to include references to type parameters anywhere within the signature of
your non-generic methods. Your method's parameters, its return types, and its internal implementation
are all able to leverage the type parameters that are part of their surrounding generic class.
You're also allowed to include generic methods within the scope of your generic C++ classes. All the
same rules that were identified for generic classes in Chapter 4, "Generic Classes," are applied to your
C++ generic methods. Instead of rehashing the rules for overloading and parameter naming here, I sug-
gest you revisit Chapter 4 for a more complete explanation of what can and cannot be achieved with
generic methods.
Default Types
In C#, you saw how the
default()
operator was used to obtain a default value for a type parameter. In
C++, the default value for a type parameter is acquired via the
()
operator. The following example
demonstrates the syntax for using this operator:
generic <typename T>
ref class DefaultClass {
public:
DefaultClass(T val) {
T testVal = T();
Console::WriteLine(L"Default Value : {0}", testVal->ToString());
}
};
Here, in the constructor of your generic class, you use the
()
operator on the
T
type parameter and
assign the result to an instance of
T
. Naturally, the default value that is returned here will vary based on
the kind of type argument that is used to construct this class. An
int
, for example, will return a
0
. If the
type parameter is a reference type, the default value will be
null
. These returned values are referred to
as "default initializers."
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:
268
Chapter 12
15_559885 ch12.qxd 9/8/05 11:06 PM Page 268