블로그는 나의 힘!


C++17. STL variant

공용체 템플릿. C++ 17 부터 추가 되었다.
간단히 말해 union의 기능이 강화된 타입이다.

 

 

 

* union ?
링크 참조 : goguri.tistory.com/entry/C-union

 

C++ union

* union ? struct가 구조체라면 union은 공용체. struct와 비슷하게 사용 하지만, 메모리를 공유한다. 예제를 보면 쉽게 이해가 되는데 struct stBUNDLE { byte btValue; short shValue; int nValue; }; 구조체 st..

goguri.tistory.com

 

variant의 큰 특징이 있다면 union은 stl을 사용할 수 없는 반면 variant는 stl을 사용해 넣을 수 있다는 점이다.
그리고 union은 메모리를 공유 하지만, variant는 타입을 나누어 초기화 시 타입에 맞게 끔 내부 설정이 되는 방식이다.
물론 관리를 철저하게 해야 되는 점이 있지만 union 보다는 편한 편이다.

 

만약 vs2017 이라면 속성에 설정을 아래와 같이 지정해야 사용 가능하다.

 

 

 


사용법 예제.
struct UserInfo
{
     wchar_t wszName[BUFFER_SIZE_64 + 1];
     int nLevel;
     int nPoint;
};

 

struct ItemInfo
{
     int nItemIndex;
     int nCount;
};

 

// 타입 선언

using stlVariant = std::variant<UserInfo,

                                        ItemInfo>;

 

void main()
{
     stlVariant _variant;

     UserInfo info;
     wsprintf( info.wszName, L"TEST_001\0" );
     info.nLevel = 1;
     info.nPoint = 100;

     // 저장
     _variant = info;

 

     // 포인터로 불러오기 (반환이 포인터이기 때문에 넣는 값도 포인터로 해야 함)
     UserInfo* pUserInfo = std::get_if(&_variant);

 

     // 레퍼런스로 불러오기
     UserInfo& userInfo = std::get(_variant);

}

 

 

 

 

 

참고 :
en.cppreference.com/w/cpp/utility/variant


occamsrazr.net/tt/entry/C17-stdvariant

 

 

std::variant - cppreference.com

template class variant; (since C++17) The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard t

en.cppreference.com

 

 

 

 

'[ Programing ] > STL & Booster' 카테고리의 다른 글

C++ STL Function  (0) 2020.09.14
C++ stl numeric_limits  (0) 2020.06.10
C++ STL shuffle.  (0) 2020.06.08
STL find_if 사용법.  (0) 2019.12.10
STL 강제 크래쉬.  (0) 2017.10.10
Posted by Mister_Q