c++ - 只让特定类 'Fabric' 构造类 'Foo' 及其所有子类的实例

标签 c++

有没有办法确保只有 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/

相关文章:

c++ - 我可以使用 memcpy 写入多个相邻的标准布局子对象吗?

c++ - Qt SQL 准备失败

c++ - 在 C++ 的宏中包装方法

c++ - 在 Windows 中可靠地写入和移动文件

c++ - 我怎样才能做 llvm 链接时间优化

c++ - 避免对非虚拟析构函数进行对象切片

c++ - 即使有填充,Sizeof 结构也不清楚

c++ - 我可以取消单例一个单例吗

c++ - 将 boost::qi::rule 与 BOOST_FUSION_ADAPT_STRUCT 一起使用的正确方法是什么?

c++ - glDrawElements 抛出异常,没有错误代码