Alias declaration

Modern C++에 적응하기
Effective Modern C++ Chapter 3. Alias declaration


alias declaration

C++98의 typedef보다 더욱 직관적이고 효과적인 type declaration 이 C++11에 도입되었다.

1
2
3
using UptrMapSS = std::unique_ptr<std::unordered_map<std::string, std::string>>;

using FP = void (*)(int, const std::string&);

type declaration 은 템플릿화 할 수 있다.

1
2
3
4
template <typename T>
using MyAllocList = std::list<T, MyAlloc<T>>;

MyAllocList<Widget> lw;

기존의 typedef를 사용하려면 조금 더 복잡하다.

1
2
3
4
5
6
template <typename T>
struct MyAllocList {
typedef std::list<T, MyAlloc<T>> type;
};

MyAllocList::type lw;

템플릿 매개변수에 의존적인 타입을 사용하려면 typedef의 경우 typename키워드를 사용해야 한다.

1
2
3
4
5
6
template <typename T>
class Widget {
private:
typename MyAllocList<T>::type list;
...
};

반면 type declaration 의 템플릿화를 사용하면 typename키워드를 앞에 붙일 필요가 없다.

1
2
3
4
5
6
7
8
9
template <typename T>
using MyAllocList = std::list<T, MyAlloc<T>>;

template <typename T>
class Widget {
private:
MyAllocList<T> list;
...
};

또한 번거롭게 ::type(내부에 선언된 typedef의 관례)역시 붙일 필요가 없다.

MyAllocListtype declaration 의 템플릿화이므로 MyAllocList<T>는 반드시 타입이어야 하고, 컴파일러도 이를 알고있다. 따라서 MyAllocList<T>비의존적 타입 이며, typename키워드를 붙일 필요가 없다.

반면, MyAllocList<T>::type이 타입이라고 컴파일러는 보장할 수 없다. MyAllocList의 특수화에서 내부에 MyAllocList<T>::type이라는 변수가 선언 되었을 수도 있기 때문이다.
따라서 MyAllocList<T>::type이 타입이라는 것은 전적으로 T에 의존한다. 그렇기 때문에 typename을 앞에 붙여야한다.


C++11 에서는 <type_traits>헤더에 타입 변환 도구가 Template meta programming 형태로 선언되어 있다.

1
2
3
std::remove_const<T>::type
std::remove_reference<T>::type
...

C++14 에서 이러한 도구들에 대한 type declaration 이 추가되었다.

1
2
3
4
5
6
template <typename T>
using std::remove_const_t = typename remove_const<T>::type;

template <typename T>
using std::remove_reference_t = typename std::remove_reference<T>::type;
...


References

Author

Joyus.Gim

Posted on

2022-07-26

Updated on

2022-07-26

Licensed under

Comments