copynull 2014. 4. 2. 16:14

boost::any

어느 타입이든지 다 담을 수 있는 자료형(단, 복사생성자 지원해야 됨)


boost::any_cast

데이터 접근시에 any_cast<자료형> 으로 접근한다.


boost::bad_any_cast

입력된 데이터의 자료형(type)이 맞지 않을 경우 예외를 발생한다




간단 사용 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// simple example
    boost::any value;
 
    value = 1;
    value = false;
    value = 1.2f;
    value = string("copynull");
 
    try
    {
        cout << boost::any_cast<string>(value) << endl;
    }
    catch (boost::bad_any_cast& e)
    {
        cout << e.what() << endl;
    }
 




array를 사용한 여러 종류의 타입들을 하나의 array에 넣는 예제


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
31
32
33
34
#include "stdafx.h"
#include <boost/any.hpp>
#include <array>
 
using namespace boost;
 
int _tmain(int argc, _TCHAR* argv[])
{
    // init array
    array<any, 10> mAnyArray = {1, 2.5f, 'a'"KOREA"};
 
    // input data
    mAnyArray[0] = string("test");
    mAnyArray[1] = 100;
    mAnyArray[2] = false;
    mAnyArray[3] = 3.14f;
 
    try
    {
        // OK
        cout << any_cast<string>(mAnyArray[0]) << endl;
 
        // Error, bad cast type
        cout << any_cast<double>(mAnyArray[1]) << endl;
    }
    catch (bad_any_cast& e)
    {
        // exception
        cout << e.what() << endl;
    }
 
    return 0;
}
 



실행 결과 (bad_any_cast 일 경우 예외가 발생한 결과를 아래와 같이 볼 수 있다)