Description
A member template is a template that is a member of a class or class template. Normally a class member is a function or data member, but it can also be a template. To see why member templates are useful, consider the following example. Suppose that you have two class types:
class A {}; class B : public A {};with an inheritance relationship between them (B objects can be assigned to A, and so on).
Suppose also that you have a template Ref, implementing some sort of a smart pointer, and template classes Ref<A> and Ref<B>. A and B have a well-defined relationship between them, but the corresponding template classes do not. That is, an object of Ref<B> cannot be assigned to a Ref<A>.
One way to resolve this issue is to define a member template in Ref:
template <class U> operator Ref<U>() { return Ref<U>(ptr); }In other words, given that we have a Ref<T>, we define a member template conversion function to convert to a type Ref<U>, where T and U are types such that a T* can be converted to a U*. In the example at hand, a B* can be converted to a A*, but not the other way around. This is the sort of relationship that we want.
The member template feature allows you to define a template that operates on types that are unrelated to the type parameters of the enclosing template. This ability is sometimes quite useful.
Concept
The sample program builds on the above example, using a Ref template that implements smart pointers. This approach allows a Ref<B> to be converted to a Ref<A>, but not a Ref<A> conversion to a Ref<B>.
Supported
Supported
Supported