http://nerv2000.tistory.com/77
어떤 자료형이든 다 넣을수 있는 그런 컨테이너
사용법은 아래와 같다...
#include <boost/any.hpp>
int
main()
{
boost::any all;
// 아래와 같이 넣으면 int형으로 변경
// 값만 써도 알아서 인식하지만 확실하게 어떤 자료형이 들어갔는지 알기 위해
all = (
int
)100;
// 이상태에서는 자료형은 안바뀌고 값만 갱신
all = 200;
// 여기서 다른 자료형으로 데이터를 넣으면 자료형도 변경 되면서 데이터 갱신
all = (
float
)1.3f;
// 값을 꺼내는 방법 첫번째 - 타입을 비교 하고 맞을때 값 꺼내기
if
( all.type() ==
typeid
(
float
) )
{
float
&output = boost::any_cast<
float
&>(all);
}
// 값을 꺼내는 방법 두번째 - try catch 문을 사용 해서 꺼내기
// 여기서는 실패에서 에러 나겠죵...
try
{
int
&otput = boost::any_cast<
int
&>(all);
}
catch
(
const
boost::bad_any_cast &e)
{
printf
(
"%s\n"
, e.what() );
}
// 변수 초기화는 요렇게???
all = boost::any();
if
( all.empty() )
{
printf
(
"아무것도 없네요\n"
);
}
return
0;
}
http://jacking.tistory.com/701
abstract
필요한 헤더
가능한 일
거의 어떤한 형(型 )이라도 저장 가능한 동적형 변수
레퍼런스
sample
#include <iostream>
#include <boost/any.hpp>
using namespace std;
struct Point
{
Point(int ix=0,int iy=0) : x(ix), y(iy) {}
int x, y;
};
static char* hw = "hello world.";
int main()
{
boost::any a, b;
a = 100; // 정수를 넣는다.
b = hw; // 문자열을 넣는다.
a = b; // any동사의 대입
b = Point(10,20); // 사용자 정의 형도 넣어보자..
// 값을 빼낸다.
cout << boost::any_cast<Point>(b).x << endl;
if( a.type() == typeid(int) )
cout << "int입니다." << endl;
else if( a.type() == typeid(char*) )
cout << "문자열입니다." << endl;
return 0;
}
출력
10.
문자열입니다.
any_cast 는 실패하면 bad_any_cast 를 던진다.
etc
생성자랑 대입 연산자가 template로 되어 있어서 넘겨진 오브젝트의 형에 따라서 대응하는 holder 클래스를 만들어 그것을 기저 클래스의 포인터에 의해서 any 중에 보관한다 라는 것으로 구현 되어 있다.
'메타프로그래밍 > Boost::' 카테고리의 다른 글
boost::bind & ref, cref (0) | 2013.02.28 |
---|---|
boost::circular_buffer (0) | 2013.02.26 |
boost::variant (0) | 2013.02.13 |
Boost::foreach (0) | 2013.01.29 |
boost::random (0) | 2013.01.29 |