Modern C++ - auto) 복습을 위해 작성하는 글 2023-11-16

rizz·2023년 11월 16일
0

Modern C++

목록 보기
1/3

📒 C++ - auto

📌 auto란?

- auto는 C++11 이전에는 자동 지역 변수를 선언하는 역할을 했지만, C++11부터는 형식이 추론되는 변수를 선언하는 역할을 한다.

- 함수 반환 형식이 변경될 때도 식의 형을 변경하여 반환할 수 있다.

 

📌 auto의 추론 규칙

// C++
	const int a = 10;
	const int& b = a;
	const int* c = &a;

	// &가 달려야 레퍼런스로 추론이 된다.
	// &가 없으면 값으로 추론이 된다.
	auto aa = a; // int
	auto& bb = b; // const int&
	auto cc = c; // const int*
// C++
#include <iostream>
#include <type_traits>

using std::cout;
using std::endl;

void func(float)
{

}

// -> decltype(t + s) : t + s를 계산할 때 나오는 타입을 리턴 타입으로 정함.
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)
{
	// underlying_type<> : enum의 기본 유형을 가져온다.
	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>

// C++
#include <iostream>

using std::cout;
using std::endl;

template<auto... Args>
auto sum(int num)
{
	return (Args + ... + num); // 3번 방식.
}

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

// C++
#include <iostream>

using std::cout;
using std::endl;

int main()
{
	// tuple packing.
	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; // t0의 0번 요소.
	cout << std::get<1>(t1) << endl; // t1의 1번 요소.

	// unpacking (C++17 이상).
	auto [x0, y1, z2] = t0;
	cout << x0 << endl;
	cout << y1 << endl;
	cout << z2 << endl;
}

Output:
1
2.1
1
2.1
3

- auto를 활용하여 간편하게 초기화할 수 있다.

profile
복습하기 위해 쓰는 글

0개의 댓글