[英]Polymorphism in C++ STL containers
I was wondering if an elegant solution exists to this problem. 我想知道这个问题是否存在优雅的解决方案。
Suppose the following: 假设如下:
class Base {
private:
int data;
protected:
Base(int data) : data(data) { }
int getData() const { return data; }
virtual bool someOp() = 0;
}
class Derived1 : public Base {
private:
int data2;
public:
Derived1(int data, int data2) : Base(data), data2(data2) { }
int getData2() const { return data2; }
bool someOp() override { /* something */ }
}
class Derived2 : public Base {
private:
float data2;
public:
Derived1(int data, float data2) : Base(data), data2(data2) { }
float getData2() const { return data2; }
bool someOp() override { /* something */ }
}
And suppose that I have the total control over the hierarchy so I can assume that Base
won't get extended, nor any DerivedX
class. 并且假设我对层次结构具有完全控制权,因此我可以假设Base
不会被扩展,也不会有任何DerivedX
类。
Now I want to store them in a std::vector
, if I want to use polymorphism I'm forced to store pointers otherwise object slicing will prevent me to store the additional derived properties. 现在我想将它们存储在std::vector
,如果我想使用多态,我会被迫存储指针,否则对象切片将阻止我存储其他派生属性。 So I'm basically forced to use a std::vector<unique_ptr<Base>>
. 所以我基本上被迫使用std::vector<unique_ptr<Base>>
。
But let's assume that I need to store plenty of these objects and I don't want to waste for double heap allocation (the internal std::vector
+ the object itself) and that at the same time I can assume that: 但是我们假设我需要存储大量这些对象,我不想浪费双堆分配(内部std::vector
+对象本身),同时我可以假设:
sizeof(DerivedX)
won't be so larger than sizeof(Base)
sizeof(DerivedX)
不会比sizeof(Base)
So I'm wondering if there is an elegant way to keep polymorphism and avoid storing pointers. 所以我想知道是否有一种优雅的方法来保持多态性并避免存储指针。 I could think of some solutions like 我可以想到一些类似的解决方案
class Base {
enum {
DERIVED1,
DERIVED2
} type;
int data;
union {
int derived1data;
float derived2data;
}
bool someOp() {
if (this->type == DERIVED1) ...
else if ..
}
}
But this is clearly not elegant. 但这显然不优雅。 I could also try to exploit the fact that object slicing shouldn't occur if sizeof(Derived) == sizeof(Base)
by using a protected union in Base
and accessing it from Derived
and casting the address to elements in the std::vector
to the desired type (according to an enum) but this sounds ugly too. 我还可以尝试利用如下事实:如果sizeof(Derived) == sizeof(Base)
通过在Base
使用受保护的联合并从Derived
访问它并将地址转换为std::vector
元素来实现到期望的类型(根据枚举),但这听起来也很难看。
Type erasure and the small buffer optimization. 键入擦除和小缓冲区优化。
You can type erase almost any property in C++, creating a custom interface that "knows" how to apply the property to a now-unknown type. 您可以在C ++中键入几乎任何属性,创建一个“知道”如何将属性应用于现在未知类型的自定义接口。
boost::any
type erases down to copy, destroy, get typeid, and cast-back-to-exactly-matching-type. boost::any
类型都会删除以复制,销毁,获取typeid和强制转换为精确匹配类型。 std::function
type erases down to copy, invoke with a specific signature, destroy, and cast-back-to-identical-type (the last is rarely used). std::function
类型擦除以复制,使用特定签名调用,销毁和反向转换为相同类型(最后很少使用)。
Free store based type erasure implementations get move semantics 'for free' by swapping around pointers. 基于免费存储的类型擦除实现通过交换指针来“免费”移动语义。
In your case, you'll want to create a "large enough" aligned storage in the type. 在您的情况下,您将需要在类型中创建“足够大”的对齐存储。 You'll want to type erase down to copy, get-as-reference-to-base, destroy and probably move (as you are storing internally). 您需要键入erase down to copy,get-as-reference-to-base,destroy并可能移动(因为您在内部存储)。
std::aligned_storage
is intended for your task (you can pass in the alignment requirements of all the types you intend to store). std::aligned_storage
适用于您的任务(您可以传递要存储的所有类型的对齐要求)。 Then in-place new the object. 然后就地新建对象。
Build a table of the operations you want to perform on the object via void*
-- copy, move, destroy, and convert-to- base*
. 通过void*
- 复制,移动,销毁和转换为base*
构建要在对象上执行的操作的表。
template<class Sig>using f = Sig*;
struct table {
f<base*(void*)> convert_to_base;
f<base const*(void const*)> convert_to_const_base;
f<void(void*,void const*)> copy_construct;
f<void(void*)> destroy;
f<void(void*,void*)> move_construct;
};
template<class T>
table const* get_table() {
static table t = {
// convert to base:
[](void*p)->base*{
T*t=static_cast<T*>(p);
return t;
},
// convert to const base:
[](void const*p)->base const*{
T const*t=static_cast<T const*>(p);
return t;
},
// etc
};
return &t;
}
now store get_table<T>()
in your type-erased instance (it is basically a virtual function table, manually implemented), and write your wrapping regular class to use the functions from the table
to manipulate the aligned_storage<?...>
. 现在将get_table<T>()
存储在类型擦除的实例中(它基本上是一个虚函数表,手动实现),并编写包装常规类以使用table
的函数来操作aligned_storage<?...>
。
Now, this can be done easier by using boost::variant
, or via something like my some type that acts like a any
without using heap storage. 现在,通过使用boost::variant
,或者像我的某些类型,就像没有使用堆存储那样的any
类型,可以更容易地做到这一点。 The some link includes an implementation that compiles of the pseudo-virtual function table technique above. 一些链接包括编译上面的伪虚函数表技术的实现。 I probably used aligned storage wrong, however, so be careful. 我可能错误地使用了对齐存储,所以要小心。
You could use std::aligned_storage to wrap your classes. 您可以使用std :: aligned_storage来包装您的类。 Assuming that Derived2 is the largest: 假设Derived2是最大的:
class Storage
{
public:
Storage(int data, int data2)
{
new (&data) Derived1(data, data2);
}
Storage(int data, float data2)
{
new (&data) Derived2(data, data2);
}
Base* getBase()
{
return reinterpret_cast<Base*>(&data);
}
~Storage()
{
getBase()->Base::~Base();
}
private:
std::aligned_storage<sizeof(Derived2)> data;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.