최대 1 분 소요

개요

  • 템플릿 클래스 객체 생성 시 타입을 명시하지 않아도 컴파일러가 자동으로 템플릿 인자 타입을 추론
  • 컴파일러가 템플릿 인자 추론 시 참조할 가이드를 제공 가능


예제

  • 코드
    #include <iostream>
    #include <string>
    #include <typeinfo>

    using namespace std;

    template <typename T> class Test1 {
        public:
            Test1(T t) { cout << typeid(t).name() << endl; }
    };

    template <typename T> class Test2 {
        public:
            Test2(T t) { cout << typeid(T).name() << endl; }
            Test2(T t1, T t2) { cout << typeid(T).name() << endl; }
    };

    Test2(const char *)->Test2<string>;

    template <typename T, typename U> Test2(T, U) -> Test2<U>;

    int main() {
        // C++14
        Test1<const char *> t1{"a"};
        Test1<string> t2{"a"};

        cout << "------" << endl;

        // C++17
        Test1 t3{"a"};
        Test2 t4{"a"};
        Test2 t5{1, 1.1};

        return 0;
    }
  • 실행 결과
    PKc
    NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
    ------
    PKc
    NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
    d