Writing a Member Function Template - C++ template

C++ examples for template:template class

Description

Writing a Member Function Template

Demo Code

class ObjectManager {
public:/*from w ww. ja va2  s  .  co m*/
   template<typename T>
   T* getObject();
   template<typename T>
   void getObject(T*& p);
};

template<typename T>
T* ObjectManager::getObject() {
   return(new T);
}

template<typename T>
void ObjectManager::getObject(T*& p) {
   p = new T;
}

class X { };
class Y { };

int main() {
   ObjectManager om;

   X* p1 = om.getObject<X>(); // You have to specify the template
   Y* p2 = om.getObject<Y>(); // parameter

   om.getObject(p1);  // Not here, though, since the compiler can
   om.getObject(p2);  // deduce T from the arguments
}

Related Tutorials