从基类的静态模板方法中调用继承类的受保护的ctor失败

max*_*dev 8 c++ inheritance templates protected

我有一个组件类,它定义了Component一般应该如何创建的静态模板方法:

class Component {
protected:
    uint32_t id;

    Component(uint32_t id) :
            id(id) {
    }

    template<typename T, uint32_t C>
    static T* createComponent() {
        // content here not relevant
        return new T(someParameter);
    }

};
Run Code Online (Sandbox Code Playgroud)

然后有一个实现,例如a Button.不应该直接使用此类的构造函数,而是使用一个调用Component::createComponent模板函数的静态方法.

class Button: public Component {
protected:
    Button(uint32_t id) :
            Component(id) {
    }
public:
    static Button* create();
};
Run Code Online (Sandbox Code Playgroud)

实现看起来像这样,将类型传递给实例化,并在创建中使用常量:

Button* Button::create() {
    return createComponent<Button, UI_COMPONENT_BUTTON>();
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,编译器抱怨"错误:'Button :: Button(uint32_t)'受到保护".根据我的理解,这个构造函数调用应该可以作为Button扩展Component,但这似乎是一个问题.

我怎么解决这个问题?

Die*_*ühl 4

由于您的create()函数无法处理进一步继承的类,您可以利用这一点,而不是创建一个Button通用的派生、受保护、派生类,该类可以访问您的protected构造函数:

class Component {
    uint32_t id;
    template <typename T>
    struct Concrete: T {
        Concrete(uint32_t id): T(id) {}
    };
protected:
    Component(uint32_t id) :
        id(id) {
    }

    template<typename T, uint32_t C>
    static T* createComponent() {
        // content here not relevant
        return new Concrete<T>(C);
    }
};

class Button:
    public Component {
protected:
    Button(uint32_t id): Component(id) {}
public:
    static Button* create() {
         return createComponent<Button, UI_COMPONENT_BUTTON>();
    }
};
Run Code Online (Sandbox Code Playgroud)