2010-07-22 81 views
2

循环std :: list时如何检查对象类型?迭代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?呸! – 2010-07-22 17:10:57

+0

因为它是私有的,所以不能输出数据。如果有方法,那么推荐的方法是使用'boost :: static_visitor'。 – UncleBens 2010-07-22 17:38:05

+0

@ Billy ONeal为什么不呢?我选择它是因为我将从列表中的任何地方移除对象。 – cpx 2010-07-22 17:54:29

回答

1

boost's own example

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; 
} 

即使用get<T>将返回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 ... 
} 
相关问题