### Member Function Templates

In Function Templates, a function template was defined outside of any template class. However, functions in C++ are often member functions of a class. If you want to create a class template and a set of function templates to go with that class template, you do not have to create the function templates explicitly, as long as the function definitions are contained within the class template. Any member function (inlined or noninlined) declared within a class template is implicitly a function template. When a template class is declared, it implicitly generates template functions for each function defined in the class template.

You can define template member functions three ways:

1. Explicitly at file scope for each type used to instantiate the template class.
2. At file scope with the template arguments.
3. Inlined in the class template itself.

Member function templates are used to instantiate any functions that are not explicitly generated. If you have both a member function template and an explicit definition, the explicit definition is used.

The template argument is not used in a constructor name. For example:

    template<class L> class Key
    {
          Key();            // default constructor
          Key( L );         // constructor taking L by value
          Key<L>( L );      // error, <L> implicit within class template
    };

The declaration Key<L>(L) is an error because the constructor does not use the template argument. Assuming this class template was corrected by removing the offending line, you can define a function template for the class template's constructor:

    // Constructor contained in function template:
    template<class L>
          Key<L>::Key(int) { /* ... */ }
          // valid, constructor template argument assumed template<class L>

          Key<L>::Key<L>(int) { /* ... */ }
          /* error, constructor template argument <L> implicit
             in class template argument */

A template function name does not include the template argument. The template argument does, however, appear in the template class name if a member function of a template class is defined or declared outside of the class template. The definition: Key<L>::Key(int) { /* ... */ } is valid because Key<L> (with template argument) refers to the class, while Key(int) { /* ... */ } refers to the member function.

Class Templates

Examples of Defining Template Member Functions
Function Templates