是否可以在 c++ 中创建类型的向量
Is it possible to create a vector of types in c++?
是否可以在 c++ 中创建类型的向量?
也许 c++11 中的 decltype 可以用于此?
我需要这个,以便我可以迭代这个向量,取类型,这就是类,并创建这样的实例。
您可以创建工厂模板:
class BaseFactory {
public:
virtual void* create() const = 0;
};
template <typename T>
class Factory :public BaseFactory {
public:
T* create() const {
return new T();
}
};
并将此类工厂实例存储在 Vector 中。但是,我认为它没有多大用处。要简单地将类型存储在向量中,请查看 boost 的 MPL 向量。
"类型向量"是什么意思——向量包含数据值,而不是类型,所以这个问题没有多大意义。
您可以创建类型的元组(元组有点像类型的向量而不是值(:
typedef std::tuple<int, int, double, std::string> mytype; // typedef a tuple type
mytype foo(4, 3, 2.0, "hello"); // create an instance
double x = get<3>(foo); // get a value from that instance
get<2>(foo) = 7; // change a value in that instance
这一切都是静态的,因为您无法动态更改变量的类型,因此一旦创建了元组类型的实例,其类型(及其元素的数量和类型(就是固定的。
你不能用简单的方式做到这一点,但可以有一些解决方法。我还不喜欢 C++11(我的 IDE 不支持它,我无法在 ATM 上更改它(,但对于旧C++,您可以使用 typeid(a).name()
,其中 a
是一个变量。您可以将函数的结果存储在vector
中,然后使用 if-else 构造创建变量。
或者 - 如果你只想初始化类的变量,那么从Base
类派生它们,该类有一个返回类类型标识符的函数:
class Base{
int classId;
public:
Base(){classID=0;};
virtual int myType(){return classID;};
};
class Derived1: public Base{
public:
Derived1(){classID=1;};
等等。然后,您只需使用 switch
语句创建对象:
vector<int> types;
// Populate the vector somewhere here
for(unsigned int i=0;i<types.size();i++){
Base* newObject;
switch(types[i].myType()){
case 0:
newObject = new Base;
break;
case 1:
newObject = new Derived;
break;
default:
newObject = 0;
}
}
也许考虑工厂函数的向量(或映射(。但是,工厂函数都需要相同的签名,并且它们需要返回某种指向基类的指针。
前任。
// factory functions
// all take no parameters and return a pointer to a shape
unique_ptr<Shape> CreateCircle();
unique_ptr<Shape> CreateSquare();
unique_ptr<Shape> CreateTriangle();
std::vector<std::function<unique_ptr<Shape>()>> factoryVector =
{
&CreateCircle,
&CreateSquare,
&CreateTriangle
};
// You can now iterate over factoryVector, invoke the () operator on each element
// of the vector, and generate a Shape pointer that points to a Circle, Square, and
// Triangle
相关文章:
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 如何在C++中创建类型列表的 n 路笛卡尔积?
- 使用 C++17,如何创建类型到值的编译时图?
- C++ 中的对象创建类型有什么区别?
- 在 C++ 中创建类型向量
- 创建类型列表并访问每种类型的静态成员?
- 无法创建类型为无序链接列表的对象
- 如何为指针创建类型定义
- 在没有宏的情况下在 C++98 中创建类型列表时遇到问题
- 使用特定成员变量值创建类型的类型
- <T> 从类型对象创建类型<T1>对象的构造函数
- 创建类型结构的指针阵列
- C++当类型T需要构造函数时,是否可以创建类型T的std::列表
- 在C++中创建类型定义
- 是否可以在 c++ 中创建类型的向量
- 创建类型为 'this'/当前对象的指针
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?
- ptr_fun - 无法创建类型?
- 如何从继承的自定义类 c++ 创建类型
- DLL 创建类型