将继承重构为模板,同时保留某些特征
Refactoring inheritance into templates while retaining certain characteristics
我有以下结构:
class Base {
virtual T foo() = 0;
};
class Derived : public Base {
T foo() override { /**/ }
}
class Derived1 : public Base {
T foo() override { /**/ }
}
我需要以下内容才能工作(或适当的替代品):
some_container<unique_ptr<Base>> objects;
基本上
C++ AMP 不允许内核中的虚拟函数,但我绝对需要类似继承链的容器行为。
这种继承链转换为模板魔术的推荐/通用模式是什么?
删除 vtable 调用的规范方法是将其替换为 switch 语句:
enum type_e
{
type_derived,
type_derived1
};
class Base
{
public:
Base( type_e type ) : m_type( type ) {}
T foo();
private:
type_e m_type;
};
T Base::Foo()
{
switch( m_type )
{
case type_derived:
return //{...} your Derived::Foo()
case type_derived1:
return //{...} your Derived1::Foo()
}
}
API 中唯一的变化是,您必须调用new Base( type_derived )
而不是调用new Derived()
。主要缺点是你现在必须将所有额外的数据(以前是Derived1或Derived的成员)保存在Base
中,这可能会使类膨胀。另一方面,您现在可以按值制作 Base 的容器,并避免 std::unique_ptr
的开销。
您可以推出自己的手动 vtable 仿真:
class Base {
protected:
using fp_t = int(*)(Base*);
fp_t fp;
Base( fp_t p ) : fp( p ) {}
public:
int foo() { return (*fp)(this); }
};
class Derived : public Base {
static int sfoo(Base* b) { return static_cast<Derived*>(b)->foo(); }
int foo() { return 42; }
public:
Derived() : Base(&sfoo) {}
};
现场示例
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 为多个会话保留XPtr
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 特征命名访问向量段
- 将特征矩阵的向量设置为0
- 保留对其他类的成员函数的引用
- 特征:模板函数中矩阵的平面图
- basic_string的前导/尾部不区分空格的特征
- 特征 3 类的模板专用化
- 特征 c++:复矩阵的面积双曲正切(atanh)
- 指针保留字符串
- C++ 中的特征向量计算
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 如何让 GCC/Clang 在保留标识符上出错
- 根据C++标准的定义实现"is_similar"类型特征
- 将继承重构为模板,同时保留某些特征
- 保留稠密特征矩阵
- 删除左值,保留左值引用(标准类型特征可用?)