Partial Template Specialization and operator->*

As I worked on this article, Esa Pulkkinen and Mark Rodgers pointed out that partial template specialization can be used to extract the object and return the type of a member function from the type of a pointer to that member function. One need merely apply the traits technique, which is widely used in the standard C++ library. (For more information on the traits technique, see Nathan Myers's article, "Traits: A New and Useful Template Technique," C++ Report, June 1995 and at http://www.cantrip .org/traits.html.)

Mark Rodgers suggested the templates in Listing Twelve for member functions taking zero or one parameters. (The extension to more parameters is straightforward.) Given these templates, PMFC can be simplified to take only one type parameter, MemFuncPtrType. That's because the other two type parametersObjectType and ReturnTypecan be deduced from MemFuncPtrType:

This leads to the revised implementation of PMFC in Listing Thirteen. Other than offering a chance to show off knowledge of traits and when typename must precede the name of a type in a template, this doesn't appear to have bought much, but don't be fooled. This greatly reduces the work smart pointer classes must do to implement operator->*. In fact, Mark Rodgers noted that a single operator->* template can support all possible member function pointers, regardless of the number of parameters taken by the member functions and whether the member functions are const. Just replace all the operator->* templates in SP (or SmartPtrBase) with the code in Listing Fourteen. The type parameter MemFuncPtrType will bind to any pointer to member function type, regardless of parameters, return type, and constness. It will then pass that type on to PMFC, where partial specialization will be used to pick the type apart.

Source code employing this approach to implementing operator- >* is available electronically.

S.M.

Back to Article
Copyright © 1999, Dr. Dobb's Journal