在Java中,我使用
ArrayList<Object> contents = new ArrayList<Object>();保存泛型类型,且元素不应是同一类型。
例如,我做了这样的事情:
int n = 1991;
String str = "mfso";
contents.add(n);
contents.add(str);现在,我想在C++中做同样的事情,但是我没有发现任何类似的东西。我试过“`void**”,但它很像C,太难驾驭了。我想要一个更有OO味道的解决方案。
我希望你能告诉我不同的解决方案,并简要地告诉我利弊。
提前感谢
KeCen周
发布于 2015-04-07 22:24:55
C++没有像Object类那样的“通用基类”。因此,这个机制必须以其他方式创建。
对于真正的“任何”容器,唯一的通用解决方案是使用来自Boost.Any库的类似于Boost.Any的东西(一些编译器可能也支持它,如std::experimental::any、如前所述)。使用它显然是有开销的,但我想这是您准备接受的事情。
下面是您如何使用它:
#include <vector>
#include <string>
#include <iostream>
#include <typeinfo>
#include <boost/any.hpp>
int main() {
std::vector< boost::any > contents;
int n = 1991;
std::string str = "mfso";
contents.emplace_back(n);
contents.emplace_back(str);
for(auto& x : contents) {
if( x.type() == typeid(int) )
std::cout << " Int: "
<< boost::any_cast< int >(x) << std::endl;
else if( x.type() == typeid(std::string) )
std::cout << " String: "
<< boost::any_cast< std::string& >(x) << std::endl;
};
};理想情况下,如果您可以以其他方式解决问题,就应该避免使用类似boost::any的东西。例如,如果所有类型的对象都通过某个基类关联(或可以关联),那么您应该使用它。或者,如果您希望存储在容器中的类型数量有限,那么您可以使用类似于boost::variant的东西(参见文档)。
发布于 2015-04-07 22:20:47
您希望使用模板。模板是一种C++语言结构,它允许编译器通过允许参数化类型(我的)来生成一个类类型或函数的多个版本。
template <class Obj>
class Foo
{
private:
Obj n;
int x;
//... more variables etc..
}执行情况:
Foo<string> t;
Foo<yourObject> s;
t.yourmethod(someParam);发布于 2015-04-08 02:50:44
如果您不希望在您的项目中使用boost的开销(如果您问我的话,这是相当大的),您可以执行以下操作:
std::vector<void*> contents;
int n = new int(9);
std::string s = new string("hello");
contents.push_back(n);
contents.push_back(s);
// get the contents
if (typeid(*contents[0]).name() == std::string("int")) {
std::cout << "contents[0] is an int" << std::endl;
}
// so on and so forth请注意,这不是C++的做事方式。如果您要尝试在C++中编写Java,您将遇到困难,所以我建议学习一种惯用的做事方法。
https://stackoverflow.com/questions/29502254
复制相似问题