C++Builder Programming Forum
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
C++빌더 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
컴포넌트/라이브러리
메신저 프로젝트
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C++빌더 강좌/문서
C++Builder Programming Tutorial&Docments
[193] [Boost 살펴보기] 2. any
Lyn [tohnokanna] 16638 읽음    2009-05-11 15:21
원본출처

http://lunapiece.net/3793
any 는 마치 스크립트 언어처럼 임의의 type을 가지는 변수를 만들 수 있다.
COM의 Varient 와도 비슷하다 하겠다.

하지만 이것을 언어수준에서 구현 해 놓았고, 다른 컨테이너와 매우 잘 맞물린다는것이 장점이라 하겠다.
vector 에 이런저런 잡데이터 쑤셔넣을때 참 좋더라
(당연히 오버헤드는 있다. 꼭 필요한 곳에만 사용하자!)


#include <cstring>
#include <cstdio>
#include <boost/any.hpp>
#include <string>
#include <vector>

using namespace boost;
using namespace std;

struct MyData
{
    int i;
    double d;
    MyData()
    {
    }
    MyData(const MyData& t) //Any의 요구사항 1 Copy Constructor
    {
        this->i = t.i;
        this->d = t.d;
    }
    MyData& operator =(const MyData &t) //Any의 요구사항 2 = operator overloading
    {
        this->i = t.i;
        this->d = t.d;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    any Data;
    //값이 비어있는지를 확인하는 방법
    if(Data.empty())
    {
        puts("Data 는 비어있음!");
    }
    else
    {
        puts("Data 는 비어있지 않음!");
    }
    Data = 3.14; //실수 리터럴의 기본 타잎은 double
    Data = 3; //정수 리터럴의 기본 타잎은 Int

    //Data = "Hello!"; //에러.
    //any 에 넣기 위해선 CopyConstructor와  = Operator Overloading 이 필요하다.
    string str = "Hello";
    Data = str; //정상적

    //Any 에 어떤 타잎이 들어있는지 확인
    //type매소드로 type 을 확인 후 any_cast 연산자를 사용하여 캐스팅
    if(Data.type() == typeid(int))
    {
        printf("Data의 Type : Int, Value : %d\n", any_cast<int>(Data));
    }
    else if(Data.type() == typeid(double))
    {
        printf("Data의 Type : Double, Value : %lf\n", any_cast<double>(Data));
    }
    else if(Data.type() == typeid(string))
    {
        printf("Data의 Type : string, Value : %s\n", any_cast<string>(Data).c_str());
    }

    //Vector 와 Any 의 복합사용예.
    printf("임의의 타잎을 담는 Vector 선언하기\n");
    vector<any> AnyVector;
    MyData myData;
    myData.d = 5.12;
    myData.i = 5;

    AnyVector.push_back(3);
    AnyVector.push_back(3.14);
    AnyVector.push_back(myData);

    vector<any>::iterator it;
    for (it = AnyVector.begin(); it != AnyVector.end(); ++it)
    {
        if(it->type() == typeid(int))
        {
            printf("Any 의 Type : Int, Value : %d\n", any_cast<int>(*it));
        }
        else if(it->type() == typeid(double))
        {
            printf("Any 의 Type : Double, : %lf\n", any_cast<double>(*it));
        }
        else if(it->type() == typeid(MyData))
        {
            printf("Any 의 Type : MyData, Value : %d, %lf\n", any_cast<MyData>(*it).i, any_cast<MyData>(*it).d);
        }
    }
    return 0;
}

+ -

관련 글 리스트
193 [Boost 살펴보기] 2. any Lyn 16638 2009/05/11
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.