8.12. Writing a Member Function Template
Problem
You have a single member function that needs to take a parameter that can be of any type, and you can’t or don’t want to be constrained to a particular type or category of types (by using a base class pointer parameter).
Solution
Use a member function template and declare a template parameter for the type of object the function parameter is supposed to have. See Example 8-13 for a short example.
Example 8-13. Using a member function template
class ObjectManager { public: template<typename T> T* gimmeAnObject(); template<typename T> void gimmeAnObject(T*& p); }; template<typename T> T* ObjectManager::gimmeAnObject() { return(new T); } template<typename T> void ObjectManager::gimmeAnObject(T*& p) { p = new T; } class X { /* ... */ }; class Y { /* ... */ }; int main() { ObjectManager om; X* p1 = om.gimmeAnObject<X>(); // You have to specify the template Y* p2 = om.gimmeAnObject<Y>(); // parameter om.gimmeAnObject(p1); // Not here, though, since the compiler can om.gimmeAnObject(p2); // deduce T from the arguments }
Discussion
When talking about function or class templates, the words parameter and argument have
some ambiguity. There are two kinds of each: template and function. Template parameters
are the parameters in the angle brackets, e.g., T
in
Example 8-13, and function parameters
are parameters in the conventional sense.
Consider the ObjectManager
class in Example 8-13. It is a simplistic version of the Factory pattern discussed in ...
Get C++ Cookbook 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.