从基类的静态模板方法中调用受保护的ctor继承类失败 [英] Calling protected ctor of inheriting class from within static template method of base class fails
问题描述
我有一个组件类定义一个静态模板方法如何创建一个组件
:
I have a component class that defines a static template method of how a Component
should be created in general:
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
模板函数。
Then there is an implementation, for example a Button
. The constructor of this class should not be used directly, instead there is a static method that calls the Component::createComponent
template function.
class Button: public Component {
protected:
Button(uint32_t id) :
Component(id) {
}
public:
static Button* create();
};
实现看起来像这样,将类型传递给实例化和创建时使用的常量: p>
The implementation looks like this, passing the type to instantiate and a constant thats used in creation:
Button* Button::create() {
return createComponent<Button, UI_COMPONENT_BUTTON>();
}
现在的问题是,编译器抱怨 'Button :: Button(uint32_t)'is protected。对我的理解,这个构造函数调用应该是OK,因为 Button
extends Component
,但这似乎是一个问题。
Now the problem is, that the compiler complains with "error: 'Button::Button(uint32_t)' is protected". For my understanding, this constructor call should be OK as Button
extends Component
, but this seems to be a problem here.
我如何解决这个问题?
推荐答案
c $ c> create()函数将不能处理进一步继承的类,你可以利用这个和不创建一个按钮
,而是一个可以访问您的 protected
构造函数的通用派生的,受保护的派生类:
Since your create()
function won't be able to deal with further inherited classes you can take advantage of this and not create a Button
but, instead, a generic derived, protected, derived class which would have access to your protected
constructor:
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>();
}
};
这篇关于从基类的静态模板方法中调用受保护的ctor继承类失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!