Member Templates

Member Templates

A function template or class template can be a member of an ordinary class, or of a class template.

Here’s an example of an Outer template class that contains an Inner template class. It makes use of the std::complex class from the C++ Standard Library.

//
//  InnerOuter.h
//  Template Classes (Member Templates)
//
//  Created by Bryan Higgs on 10/19/24.
//

#ifndef InnerOuter_h
#define InnerOuter_h

#include <iostream>
#include <complex>

template <class T>
class Outer
{
public:
  Outer( std::complex<double> c, double d)
    : m_inner(c, d)
  {}

  template <class U>
  U min(U v1, U v2)
  {
    return (v1 < v2) ? v1 : v2;
  }
  
  std::complex<double> getValue1() const
  {
    return m_inner.getValue1();
  }
  
  double getValue2() const
  {
    return m_inner.getValue2();
  }

private:
  
  template <class TYPE>
  class Inner
  {
  public:
    Inner(TYPE v1, T v2) 
      : m_value1(v1), m_value2(v2) {}
    
    TYPE getValue1() const 
    {
      return m_value1;
    }
    
    T getValue2() const
    {
      return m_value2;
    }
    
  private:
    TYPE m_value1;
    T    m_value2;
  };

  Inner< std::complex<double> > m_inner;
    // NOTE THE AVOIDANCE OF >> !,
    // which was necessary in some earlier
    // versions of C++. Modern C++ compilers do
    // not have a problem with this.
};

#endif /* InnerOuter_h */

… and a main program that exercises these template classes:

//
//  main.cpp
//  Template Classes (Member Templates)
//
//  Created by Bryan Higgs on 10/19/24.
//

#include <iostream>
#include <complex>
#include "InnerOuter.h"

int main(int argc, const char * argv[])
{
  Outer<double> o1( std::complex<double>(23.4, 11.7), 56.8 );
  
  int i1 = 5, i2 = 4;
  int val = o1.min(i1, i2);
  
  std::cout << "min(" << i1 << "," << i2 << ") = "
            << val << std::endl;

  std::cout << "o1: value1 (complex<double>) : "
            << o1.getValue1() << "," << std::endl
            << " value2 (double) : "
            << o1.getValue2() << std::endl;
  
  return 0;
}

It produces the following output:

min(5,4) = 4
o1: value1 (complex<double>) : (23.4,11.7),
 value2 (double) : 56.8
Program ended with exit code: 0