📒 C++ - auto
📌 auto란?
- auto는 C++11 이전에는 자동 지역 변수를 선언하는 역할을 했지만, C++11부터는 형식이 추론되는 변수를 선언하는 역할을 한다.
- 함수 반환 형식이 변경될 때도 식의 형을 변경하여 반환할 수 있다.
📌 auto의 추론 규칙
const int a = 10;
const int& b = a;
const int* c = &a;
auto aa = a;
auto& bb = b;
auto cc = c;
#include <iostream>
#include <type_traits>
using std::cout;
using std::endl;
void func(float)
{
}
template<typename T, typename S>
auto add(T t, S s) -> decltype(t + s)
{
return t + s;
}
enum class Type
{
A, B
};
template<typename Enumeration>
auto asInteger(Enumeration value)
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
int main()
{
int nums[] = { 1,2,3 };
auto nums0 = nums;
auto& nums1 = nums;
auto func0 = func;
auto& func1 = func;
cout << add(1, 1.2) << endl;
cout << asInteger(Type::A) << endl;
}
- auto를 함수의 반환 값으로 사용하여 유동적인 자료형을 반환할 수 있도록 하였다.
- enum의 타입에 따라 캐스팅하여 반환할 수도 있다.
📌 template<auto... Args>
#include <iostream>
using std::cout;
using std::endl;
template<auto... Args>
auto sum(int num)
{
return (Args + ... + num);
}
int main()
{
int num = 5;
cout << sum<10, 2, 1, 30>(num);
}
Output:
48
- 매개변수의 개수가 정해지지 않았을 때, template과 함께 활용할 수 있다.
표현식 = 실제 계산 방식
1. Args + ... = (A[0] + (A[1] + (A[2] + ... (A[n - 1] + A[n])
2. ... + Args : (A[0] + A[1]) + A[2]) + A[3]) ... + A[n])
3. Args + ... + B : (A[0] + (A[1] + (A[2] + ... (A[n - 1] + A[n] + B)
4. B + ... + Args : (B + A[0]) + A[1]) + A[2]) + A[3) ... + A[n])
📌 auto를 활용한 packing과 unpacking
#include <iostream>
using std::cout;
using std::endl;
int main()
{
std::tuple<int, float, std::string> t0{ 1,2.1f, "3" };
auto t1 = std::make_tuple(1, 2.1f, "3");
cout << std::get<0>(t0) << endl;
cout << std::get<1>(t1) << endl;
auto [x0, y1, z2] = t0;
cout << x0 << endl;
cout << y1 << endl;
cout << z2 << endl;
}
Output:
1
2.1
1
2.1
3
- auto를 활용하여 간편하게 초기화할 수 있다.