6.8. Member Template Functions

It is also possible to define a member template function. Let’s look at an example and then walk through it:

class PrintIt { 
public: 
    PrintIt( ostream &os ) 
           : _os( os ){} 

    // a member template function 
    template <typename elemType> 
    void print( const elemType &elem, char delimiter = '\n' ) 
              { _os << elem << delimiter; } 
private: 
    ostream& _os; 
}; 

PrintIt is a nontemplate class that is initialized to an output stream. It provides a member template print() function that writes an object of an arbitrary type to that output stream. By making print() a member template function, we can provide a single instance that supports any type for which an instance of the output operator can be applied. Were we to parameterize PrintIt ...

Get Essential C++ 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.