有没有一种方法可以确保仅类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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句