Updated:

less than 1 minute read

개요

  • 타입 추론
  • C++11
    • 변수, 람다 파라미터
  • C++14
    • 함수 리턴
  • C++20
    • 파라미터


예제

  • 코드
     #include <cstring>
     #include <iostream>
     #include <string>
        
     using namespace std;
        
     // C++11
     template <typename T> auto func1(T t) -> decltype(t) { return t; }
        
     // C++14
     template <typename T> auto func2(T t) { return t; }
        
     // C++20
     auto func3(auto t) { return t; }
        
     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);
     }
        
     int main() {
     	auto i = 0;
     	auto c = 'a';
     	auto s = "abc";
        
     	cout << type_name<decltype(i)>() << endl;
     	cout << type_name<decltype(c)>() << endl;
     	cout << type_name<decltype(s)>() << endl;
        
     	cout << "------" << endl;
        
     	cout << func1(1) << endl;
     	cout << func2(2) << endl;
     	cout << func3(3) << endl;
        
     	return 0;
     }
    
  • 실행 결과
     int
     char
     const char*
     ------
     1
     2
     3