在C ++中存储任意对象的列表 [英] Storing a list of arbitrary objects in C++
问题描述
在Java中,您可以有一个对象列表。您可以添加多个类型的对象,然后检索它们,检查它们的类型,并对该类型执行相应的操作。
例如:(如果代码不完全正确,从内存中删除)
In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type.
For example: (apologies if the code isn't exactly correct, I'm going from memory)
List<Object> list = new LinkedList<Object>();
list.add("Hello World!");
list.add(7);
list.add(true);
for (object o : list)
{
if (o instanceof int)
; // Do stuff if it's an int
else if (o instanceof String)
; // Do stuff if it's a string
else if (o instanceof boolean)
; // Do stuff if it's a boolean
}
复制此行为的最佳方式
推荐答案
使用Boost.Variant和访问者的示例:
Your example using Boost.Variant and a visitor:
#include <string>
#include <list>
#include <boost/variant.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;
typedef variant<string, int, bool> object;
struct vis : public static_visitor<>
{
void operator() (string s) const { /* do string stuff */ }
void operator() (int i) const { /* do int stuff */ }
void operator() (bool b) const { /* do bool stuff */ }
};
int main()
{
list<object> List;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
BOOST_FOREACH (object& o, List) {
apply_visitor(vis(), o);
}
return 0;
}
使用这种技术的一个好处是,另一个类型到变体,你忘记修改一个访问者以包括该类型,它将无法编译。您已支持所有可能的情况。而如果你使用switch或cascading if语句,很容易忘记在任何地方进行更改并引入一个错误。
One good thing about using this technique is that if, later on, you add another type to the variant and you forget to modify a visitor to include that type, it will not compile. You have to support every possible case. Whereas, if you use a switch or cascading if statements, it's easy to forget to make the change everywhere and introduce a bug.
这篇关于在C ++中存储任意对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!