[boost]any - 다양한 데이터 형을 포함할 수 있는 컨테이너
Posted 2009/02/02 10:53|
|
|
댓글 하나가 운영자에겐 커다란 힘이 됩니다!
일반적으로 STL에서 제공하는 컨테이너 객체에는 오직 하나의 데이터 형만을 저장할 수 있습니다.
예를 들면, vector<string>, vector<int> 와 같이 말이지요.
하지만, boost에서 제공하는 any 클래스를 사용하면, 하나의 컨테이너 객체에 다양한 데이터 형을 저장할 수 있습니다.
그리고, 다음은 boost::any 클래스의 설명을 도와줄 예제 입니다.
#include <boost/any.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using boost::any;
using boost::any_cast;
typedef struct foo
{
int m_nVal;
} foo;
int main(void)
{
int n = 10;
bool b = true;
vector<any> av;
vector<any>::iterator it;
foo f;
f.m_nVal = 100;
av.push_back(n); // store int
av.push_back(b); // store bool
av.push_back(string("string")); // store string
av.push_back(f); // store struct
for ( it = av.begin(); it != av.end(); it++ )
{
any &a = *it;
if ( a.type() == typeid(int) )
{
int *val = any_cast<int>(&a);
cout << "int : " << *val << endl;
}
else if( a.type() == typeid(bool) )
{
const bool *val = any_cast<bool>((const any *)&a);
cout << "bool : " << *val << endl;
}
else if( a.type() == typeid(string) )
{
string val = any_cast<string>(a);
cout << "str : " << val << endl;
}
else if( a.type() == typeid(struct foo) )
{
struct foo val = any_cast<struct foo>(a);
cout << "foo : " << val.m_nVal << endl;
}
}
return 0;
}
[참고] http://www.boost.org/doc/libs/1_37_0/doc/html/any.html
출처 : http://blog.daum.net/aswip/8429308위의 정보가 도움이 되셨나요? 그렇다면 댓글 하나만 남겨주세요.
댓글 하나가 운영자에겐 커다란 힘이 됩니다!
- Filed under : 프로그래밍/C & Cpp
- Tag : boost any
- Comment Trackback

