2

std::list をループするとき、どのようにオブジェクト タイプをチェックしますか?

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

2 に答える 2

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

つまり、を使用get<T>すると a が返されT*ます。そうT*でない場合nullptr、バリアントのタイプはTです。

于 2010-07-22T17:10:00.393 に答える
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 ...
}
于 2010-07-22T17:10:49.097 に答える