仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
Only let the specific class 'Fabric' construct instances of class 'Foo' and all of its subclasses
有没有办法确保只有类Fabric
可以构造类Foo
及其所有子类,而不必在每个子类中声明私有构造函数和friend class Fabric
?
struct Foo {
friend class Fabric;
protected:
Foo() = default;
};
struct FooConcrete1 : Foo {
friend class Fabric;
protected:
Foo() = default;
};
由于友谊不是继承的,因此在声明每个子类时似乎都需要两个手动操作,这很容易出错。
一种选择是声明一个只能通过Fabric
构造的标签结构,并将此对象传递给Foo
的构造函数。如果忘记将构造函数添加到派生类,则会收到一个错误,指出Foo
不是默认可构造的。
struct FooTag
{
friend struct Fabric;
private:
FooTag();
};
struct Foo {
Foo(FooTag tag) {}
};
struct FooConcrete1 : Foo {
using Foo::Foo;
};
struct Fabric
{
void test()
{
FooConcrete1 f = FooConcrete1(FooTag());
}
};
int main()
{
FooConcrete1 f; // can't construct as we can't construct FooTag
return 0;
}
相关文章:
- 仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
- 无法将模板子类强制转换为其他模板实例化
- 创建子类的多个实例,其中只有一个超类实例
- 是具有接口专用化的子类多态的模板实例化
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 返回具体子类实例的 C++ 虚拟类函数
- 是否可以为所有子类设置一个实例?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 从C++中的父类实例访问子类方法
- 如何使用 QList 跟踪子类的实例
- 如何有条件地实例化不同的父/子类
- 声明基类类型的指针,但随后通过指向子类来实例化它.这是良好的编程实践吗?
- 创建 QQuickItem 子类的实例是否有问题,我不打算渲染或添加到 QML 树中的实例?
- 将子类实例替换为超类引用 c++
- 如何防止调用函数调用正在被销毁的子类实例
- 制作不同子类实例的向量
- 使用move语义将基类实例推入子类实例
- c++继承:子类实例同时使用子和父构造函数
- 无法将子类实例作为参数而不是超类传递
- 从子类实例访问和更改父值