仅让特定类'Fabric'构造类'Foo'及其所有子类的实例

Only let the specific class 'Fabric' construct instances of class 'Foo' and all of its subclasses

本文关键字:子类 实例 Fabric Foo      更新时间:2023-10-16

有没有办法确保只有类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;
}