【发布时间】:2015-02-16 04:51:48
【问题描述】:
我有一个组件类,它定义了一个静态模板方法,一般来说应该如何创建 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);
}
};
然后有一个实现,例如Button。这个类的构造函数不能直接使用,而是有一个静态方法调用Component::createComponent模板函数。
class Button: public Component {
protected:
Button(uint32_t id) :
Component(id) {
}
public:
static Button* create();
};
实现看起来像这样,传递要实例化的类型和创建时使用的常量:
Button* Button::create() {
return createComponent<Button, UI_COMPONENT_BUTTON>();
}
现在的问题是,编译器抱怨 “错误:'Button::Button(uint32_t)' is protected”。据我了解,这个构造函数调用应该没问题,因为Button 扩展了Component,但这似乎是一个问题。
我该如何解决这个问题?
【问题讨论】:
-
你标题的复杂性让我崩溃了,但这是个好问题。
-
我无法想象一个更简单的描述基本问题的方法:D
-
好吧,你的构造函数没有做任何'Create'方法不能做的事情,所以不要使用任何Ctor?
-
问题是还有一个
Window类不使用createComponent函数,虽然我还是想强制它把id传给构造函数。但是,是的,你是对的,我可以将该逻辑添加到模板函数中。 :) 谢谢!
标签: c++ templates inheritance protected