是否可以在 c++ 中创建类型的向量

Is it possible to create a vector of types in c++?

本文关键字:创建 类型 向量 c++ 是否      更新时间:2023-10-16

是否可以在 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