1 분 소요

개요

  • 전달된 식의 값 종류에 따른 타입을 컴파일 타임에 추론하여 치환
  • 값 종류
    • l-value
      • 이동이 불가능한 l-value
      • T&로 추론
    • pr-value
      • 순수 r-value
      • T로 추론
    • x-value
      • 이동이 가능한 l-value
      • T&&로 추론
  • auto의 경우 정확하게 추론하지 않음


예제

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

    using namespace std;

    template <typename T> constexpr string type_name() {
    	const string s = __PRETTY_FUNCTION__;
    	const int prefixSize = s.find("[with T = ") + strlen("[with T = ");

    	return string(s.data() + prefixSize, s.find(';') - prefixSize);
    }

    template <typename T1, typename T2>
    void add(T1 t1, T2 t2, decltype(t1 + t2) &result) {
    	result = t1 + t2;
    }
    template <typename T1, typename T2>
    auto add(T1 t1, T2 t2) -> decltype(t1 + t2) {
    	return t1 + t2;
    }

    int main() {
    	int a = 1;
    	auto b1 = a;
    	decltype(a) b2 = a;
    	cout << type_name<decltype(b1)>() << endl;
    	cout << type_name<decltype(b2)>() << endl;

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

    	int &c = a;
    	auto d1 = c;
    	decltype(c) d2 = c;
    	cout << type_name<decltype(d1)>() << endl;
    	cout << type_name<decltype(d2)>() << endl;

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

    	int &&e = 3;
    	auto f1 = e;
    	decltype(e) f2 = 4;
    	cout << type_name<decltype(f1)>() << endl;
    	cout << type_name<decltype(f2)>() << endl;

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

    	int g = 1, h = 2;
    	auto i1 = g + h;
    	decltype(g + h) i2 = g + h;
    	cout << type_name<decltype(i1)>() << endl;
    	cout << type_name<decltype(i2)>() << endl;

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

    	int j = 1;
    	auto k1 = j;
    	decltype((j)) k2 = g;
    	cout << type_name<decltype(k1)>() << endl;
    	cout << type_name<decltype(k2)>() << endl;

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

    	const int l = 1;
    	auto m1 = l;
    	decltype(l) m2 = l;
    	cout << type_name<decltype(m1)>() << endl;
    	cout << type_name<decltype(m2)>() << endl;

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

    	int result = 0;
    	add(1, 2, result);
    	cout << result << endl;

    	cout << type_name<decltype(add(1, 2))>() << endl;
    	cout << type_name<decltype(add(1, 1.1))>() << endl;

    	return 0;
    }
  • 실행 결과
    int
    int
    ------ 1
    int
    int&
    ------ 2
    int
    int&&
    ------ 3
    int
    int
    ------ 4
    int
    int&
    ------ 5
    int
    const int
    ------ 6
    3
    int
    double