티스토리 뷰

 C++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++
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함