http://blog.naver.com/sorkelf?Redirect=Log&logNo=40135048244
C++에 Union같이 복수의 형태의 변수를 같은 영역에 넣는 것
Union과의 차이는 생성자의 필요한 객체도 저장이 가능하다는 것.
(Union에서는 예를들면 std::string은 쓸 수 없음)
또한 which()멤버함수를 써서 내부에 무엇이 들어있는지 알수 있다는 것
boost::any도 비슷한 역할을 한다.
Variant는 실체 형태가 실행시에 동적으로 변화는 일종의 다양한 형태도 생각할수 있기
때문에 Visitor패턴을 구현할 때 상당히 편리하다.
#include <iostream>
#include <string>
#include <boost/variant.hpp>
using namespace std;
// 「2배 하는 」Visitor
struct do_double : boost::static_visitor<void>
{
template<typename T>
void operator()( T& t ) const { t = t + t; }
};
int main()
{
boost::variant<int,double,string> v;
v = -2;
//이 값이 int 인지 확인
assert( v.which() == 0 );
//int를 꺼낸다
cout << boost::get<int>(v) << endl;
v = 3.14;
//이 값이 double인지 확인
assert( v.which() == 1 );
//표시만 할거라면 get<..>은 필요없음
cout << v << endl;
v = "VANICA";
//값이 string인지 확인
assert( v.which() == 2 );
//Visitor를 던진다
boost::apply_visitor( do_double(), v );
cout << v << endl;
return 0;
}
예제)
결과
위의 예에서는 int와 double,string중에 하나가 들어있는 변수 v를 사용하고 있다
특수한 기법이 필요하긴 하지만 재귀적인 variant도 쓸 수 있다
아래에 예는 리프노드가 int로 되어있는 이진트리를 정의하고 있다.
typedef make_recursive_variant<
int, pair<recursive_variant_, recursive_variant_>
>::type binary_tree;
// binary_tree ≒ variant<,int,pair<binary_tree,binary_tree>>
반응형
'메타프로그래밍 > Boost::' 카테고리의 다른 글
boost::circular_buffer (0) | 2013.02.26 |
---|---|
boost::any (0) | 2013.02.13 |
Boost::foreach (0) | 2013.01.29 |
boost::random (0) | 2013.01.29 |
Boost::mpl (0) | 2012.12.25 |