Template

함수에서 템플릿 사용법

#include <string>

template<typename T>
T sum(const T& a, const T& b) {
  return a + b;
}

// std::string 만 다르게: "hello" + ", " + "world" 형태
template<>
std::string sum<std::string>(const std::string& a, const std::string& b) {
  return a + ", " + b;
}

auto n = sum(1, 2);                    // int, 3
auto s = sum(std::string("a"), std::string("b"));  // "a, b"

클래스에서 템플릿 사용법

template<typename T>
class Box {
 public:
  T value;
  explicit Box(const T& v) : value(v) {}

  T get() const { return value; }
};

Box<int> a(10);
Box<std::string> b("hello");
  • Box<int>, Box<std::string>처럼 타입을 바꿔 같은 클래스를 재사용합니다.
  • 템플릿 클래스도 함수 템플릿처럼 typename T 자리에 실제 타입이 들어갑니다.