TITLE: intro to member templates [ This material is excerpted with permission from the author Glen McCluskey. See the trailer for contact info. -adc ] NEW C++ FEATURE - MEMBER TEMPLATES In chapter 14 of the draft ANSI/ISO C++ standard is a mention of something called member templates. This feature is new in a way and not yet widely available, but worth mentioning here. Member templates are simply a generalization of templates such that a template can be a class member. For example: #include template struct Pair { A a; B b; Pair(const A& ax, const B& bx) : a(ax), b(bx) {} template Pair(const Pair& p) : a(p.a), b(p.b) {} }; int main() { Pair x(37, 12.34); Pair y(x); printf("%ld %Lg\n", y.a, y.b); return 0; } This is an adaptation of a class found in the Standard Template Library. Note that an object of class Pair is constructed from an object of class Pair. By using a template constructor it is possible to construct a Pair from any other Pair, assuming that conversion from T to A and U to B are supported. Without the availability of template constructors one could only declare constructors with fixed types like "Pair(int)" or else use the template arguments to Pair itself, as in "Pair(A, B)". In a similar way to function template use, it's possible to have usage like: template struct A { template struct B {/* stuff */}; }; A::B ab; In this example, the type value of T within the nested template declaration would be "double", while the value of U would be "long". There are a few restrictions on member templates. A destructor for a class cannot be defined as a function template, nor may a function template member of a class be virtual. [ This information came from the C++ Newsletter available free over the net. Issue #009 April, 1996 SUBSCRIPTION INFORMATION / BACK ISSUES To subscribe to the newsletter, send mail to majordomo@world.std.com with this line as its message body: subscribe c_plus_plus Back issues are available via FTP from: rmii.com /pub2/glenm/newslett or on the Web at: http://www.rmii.com/~glenm There is also a Java newsletter. To subscribe to it, say: subscribe java_letter using the same majordomo@world.std.com address. ------------------------- Copyright (c) 1996 Glen McCluskey. All Rights Reserved. This newsletter may be further distributed provided that it is copied in its entirety, including the newsletter number at the top and the copyright and contact information at the bottom. ]