gpt4 book ai didi

c++ - 迭代 std::list

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:00:19 25 4
gpt4 key购买 nike

循环 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
}
}

最佳答案

来自 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 .

关于c++ - 迭代 std::list<boost::variant>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3311399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com