티스토리 뷰
C++/Effective Modern C++
[Effective Modern C++] 항목 9. typedef보다 별칭 선언을 선호하라
pppgod 2019. 9. 28. 21:04C++11에는 별칭 선언(alias declaration)을 제공한다. 별칭 선언이란 typedef를 대체할 수 있으면서 몇가지 장점들이 있다. 먼저 둘의 차이를 보자.
typedef std::unique_ptr<std::unordered_map<std::string, std::string>> UPtrMapSS;
using UPtrMapSS = std::unique_ptr<std::unordered_map<std::string, std::string>>;
typedef보다 별칭 선언을 선호해야하는 이유는 바로 별칭 템플릿(alias templates) 때문이다.
template<typename T>
using MyAllocList = std::list<T, MyAlloc<T>>;
template<typename T>
struct MyAllocList {
typedef std::list<T, MyAlloc<T>> type;
};
당장 위에만 봐도 별칭 선언을 사용한 경우가 간단하다. 게다가 이를 다른 클래스에서 사용하려면 이름 앞에 typename을 꼭 붙여야한다. 그러나 별칭 템플릿으로 선언한다면 매우 간단해진다.
template<typename T>
class Widget {
private:
typename MyAllocList<T>::type list; // typedef
MyAllocList<T> list; // 별칭 템플릿
}
여기까지는 그래도 복잡하기만 할 뿐 사용하는데는 문제가 없다. 하지만 다른곳에서 문제가 생길 수 있다.
class Wine { ... };
template<>
class MyAllocList<Wine> {
private:
enum class WineType
{ White, Red, Rose };
WineType type;
...
};
위와 같이 선언하는 경우 type이 중복되어서 WineType을 가져오게 된다. 위와 같은 문제가 C++11의 STL에도 존재하였다.
STL
문제가 되는 stl은 아래와 같다.
std::remove_const<T>::type
std::remove_reference<T>::type
std::add_lvalue_reference<T>::type
위에서 예시로 든 코드처럼 type을 사용하고 있다. 이는 위와 같이 문제가 발생할 수 있다. 그래서 C++14에서는 아래의 stl이 추가되었다.
std::remove_const_t<T>
std::remove_reference_t<T>
std::add_lvalue_reference_t<T>
참고 서적
스콧 마이어스, Effective Modern C++
'C++ > Effective Modern C++' 카테고리의 다른 글
[Effective Modern C++] 항목 11. 정의되지 않은 비공개 함수보다 삭제된 함수를 선호하라 (0) | 2019.10.07 |
---|---|
[Effective Modern C++] 항목 10. 범위 없는 enum보다 범위 있는 enum을 선호하라 (0) | 2019.09.28 |
[Effective Modern C++] 항목 7. 객체 생성 시 괄호(())와 중괄호({})를 구분하라 (0) | 2019.09.21 |
[Effective Modern C++] 항목 6. auto가 원치 않은 형식으로 연역될 때에는 명시적 형식의 초기치를 사용하라 (0) | 2019.09.08 |
[Effective Modern C++] 항목 5. 명시적 형식 선언보다는 auto를 선호하라 (0) | 2019.09.08 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 발아시기
- 보편참조
- 다이소
- std::move
- Effective Modern C++
- Forwarding
- Unreal
- thread
- Join
- const
- 보편 참조
- auto
- C
- C++11
- Future
- C++14
- detach
- 포인터
- Perfect
- CPP
- std::forward
- C++
- Overloading
- 람다
- async
- forward
- Modern
- Override
- Effective
- MOVE
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함