C++/Templates 2021. 3. 21. 23:58

함수 템플릿 (Function Templates)

  • template<typename T>, template<class T>의 형태로 템플릿을 선언할 수 있다.

예제

  #include <iostream>

  template<typename T>
  T    getMax(T x, T y)
  {
    return (x > y) ? x : y;
  }

  class Cents
  {
      int    cents_;

  public:
      Cents(int cents = 0) { cents_ = cents; }

      bool    operator > (const Cents& c)
      {
          return (cents_ > c.cents_);
      }

      friend std::ostream& operator << (std::ostream& out, const Cents& cents)
      {
          out << cents.cents_ << " cents";
          return (out);
      }
  };

  int        main()
  {
    using namespace std;

    cout << getMax(1, 2) << endl;
    cout << getMax(3.14, 1.592) << endl;
    cout << getMax(1.0f, 3.4f) << endl;
    cout << getMax('a', 'c') << endl;
    cout << getMax(Cents(5), Cents(9)) << endl;
  }

  /* stdout
  2
  3.14
  3.4
  c
  9 cents
  */