有没有办法确保只有 Fabric
类才能构造 Foo
类及其所有子类,而不必声明私有(private)构造函数和 每个子类中的 friend 类 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;
}
关于c++ - 只让特定类 'Fabric' 构造类 'Foo' 及其所有子类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903357/