迭代 std::list
循环 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
}
}
How would you check for the object type when looping 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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 boost 自己的示例:
即使用
get
将返回T*
。如果T*
不是nullptr
,则变体的类型为T
。From boost's own example:
i.e. Using
get<T>
will return aT*
. IfT*
is notnullptr
, then the variant is of typeT
.与确定常规变体类型的方式相同。
Same as how you determine the type from a regular variant.