构造不同类型的C++向量数组

Constructing array of C++ vectors of different types

本文关键字:C++ 向量 数组 同类型      更新时间:2023-10-16

有没有一种很好的方法来构造不同类型的std::vector数组?还有没有存储这些向量的好方法?

例如,让我们有一些结构体FooBarBaz。我想创建一个容器类Cont,其中包含FooBarBaz向量的某种组合。下面的代码将实现这一点,但我有一些问题。

#include <vector>
// arbitrary structs
struct Foo{ int var1; };
struct Bar{ double var1; double var2; };
struct Baz{ char var1; float var2; };
enum Mask{
fooMask = (1<<0),
barMask = (1<<1),
bazMask = (1<<2)
};
class Cont{
void** containers;
public:
Cont(int mask){
// count number of 1s in mask
int count = 0;
int countMask = mask;
while(countMask){
countMask &= countMask-1; // unset rightmost 1
count++;
}
containers = new void*[count];
int index = 0;
if((mask & fooMask) == fooMask)
containers[index++] = new std::vector<Foo>;
if((mask & barMask) == barMask)
containers[index++] = new std::vector<Bar>;
if((mask & bazMask) == bazMask)
containers[index++] = new std::vector<Baz>;
}
};
int main(){
// example construction
Cont c1(fooMask);
Cont c2(barMask|bazMask);
return 0;
}

首先,我不喜欢我必须将向量数组存储在空白**中,但我找不到更好的方法。

其次,如果我添加一个名为Qux的新结构,我将不得不修改Cont构造函数。最好是为了可维护性,我希望构造数组,而不必将结构类型硬编码到Cont类中。

我尝试使用模板来解决这个问题,但找不到我满意的解决方案。我担心Cont成为模板,因为我认为这会导致每个结构组合的模板膨胀。此外,我将有多个Cont对象,但每个组合中只有一个我需要。

您可以使用类型擦除。

struct ContainerBase
{
virtual ~ContainerBase() = 0;
// This is where you can add an interface for common functionality.
// Write the pure virtual functions here and implement/override them in ContainerTyped.
};
inline ContainerBase::~ContainerBase() = default;
template<class T>
struct ContainerTyped : public ContainerBase
{
std::vector<T> values;
};
class Cont
{
std::vector<std::unique_ptr<ContainerBase>> containers;
public:
Cont(int mask) {
// ...
if ((mask & fooMask) > 0)
containers.push_back(std::make_unique<ContainerTyped<Foo>>());
if ((mask & barMask) > 0)
containers.push_back(std::make_unique<ContainerTyped<Bar>>());
}
};

演示

这可能比使用例如std::any或其他预先存在的类型擦除,因为 1( 您指定只能存储特定的东西(您的矢量容器(,以及 2( 您可以按照指示添加通用接口,甚至可以将接口功能专用于不同的ContainerTyped。但是我们需要更多地了解您的用例,以详细说明此优势。

void*的问题始终是您需要以某种方式保留有关实际存储的内容的信息,因为您正在绕过强类型系统。换句话说,如何将存储的东西放回强类型系统中?这正是上述方法可以大放异彩的部分,因为您可以在ContainerBase中添加virtual print() = 0,然后为每种结构创建专用版本,例如

template<>
void ContainerTyped<Foo>::print()
{
for (Foo& foo : values) {
// Print Foo objects as you wish!
}
}

就添加Qux结构时不必接触Cont构造函数而言,显然仍然需要以某种方式对"哪个掩码位属于哪个结构"的信息进行编码,但您可以从Cont构造函数中提取它(甚至将其隐藏在不同的翻译单元中(:

// Put this implementation wherever, Cont only has to know the signature.
std::unique_ptr<ContainerBase> makeContainer(int mask, unsigned indexBit)
{
if ((mask & fooMask) > 0)
return std::make_unique<ContainerTyped<Foo>>();
// etc.
if ((mask & quxMask) > 0)
return std::make_unique<ContainerTyped<Qux>>();
return nullptr;
}
// ...
Cont::Cont(int mask)
{
for (unsigned indexBit = 0; indexBit < 8; ++indexBit) {
auto container = makeContainer(mask, indexBit);
if (container)
containers.emplace_back(std::move(container));
}
}

你可以通过其他方式对枚举 -> 类型信息进行编码,但这超出了这个问题的范围。关键是您可以将具体类型隐藏在ContainerBase后面,并在您想要引用"这些容器中的任何一个"的任何地方使用它。