2010-07-22 6 views
2

std :: list를 반복 할 때 개체 유형을 어떻게 확인합니까? boost's own example에서std :: list <boost :: variant>

class A 
{ 
    int x; int y; 
public: 
    A() {x = 1; y = 2;} 
}; 

class B 
{ 
    double x; double y; 
public: 
    B() {x = 1; y = 2;} 
}; 

class C 
{ 
    float x; float y; 
public: 
    C() {x = 1; y = 2;} 
}; 

int main() 
{ 
    A a; B b; C c; 
    list <boost::variant<A, B, C>> l; 
    l.push_back(a); 
    l.push_back(b); 
    l.push_back(c); 

    list <boost::variant<A, B, C>>::iterator iter; 

    for (iter = l.begin(); iter != l.end(); iter++) 
    { 
      //check for the object type, output data to stream 
    } 
} 
+3

std :: list? 왝! –

+0

그 자체이므로 데이터를 출력 할 수 없습니다. 방법이 있다면, 그것을하기위한 권장 방법은'boost :: static_visitor'를 이용하는 것입니다. – UncleBens

+0

@ Billy ONeal 왜 안 되니? 나는 목록의 어느 곳에서나 객체를 제거 할 것이기 때문에 그것을 선택했다. – cpx

답변

1

:

void times_two(boost::variant< int, std::string > & operand) 
{ 
    if (int* pi = boost::get<int>(&operand)) 
     *pi *= 2; 
    else if (std::string* pstr = boost::get<std::string>(&operand)) 
     *pstr += *pstr; 
} 

, 즉 T*를 반환합니다 get<T> 사용. T*nullptr이 아닌 경우 변형은 T입니다.

1

일반 변형에서 유형을 결정하는 것과 같습니다.

for (iter = l.begin(); iter != l.end(); iter++) 
{ 
     //check for the object type, output data to stream 
     if (A* a = boost::get<A>(&*iter)) { 
      printf("%d, %d\n", a->x, a->y); 
     } else ... 
} 
관련 문제