抽象类和静态方法
我有一个抽象类:
class A
{
public:
bool loaded_;
virtual int load() = 0;
}
和几个派生类:
class B:public A
{
public:
int load();
static B& instance();
}
class C:public A
{
public:
int load();
static C& instance();
}
事实是 ::instance() 方法内的代码对于每个类都是相同的:
static B& B::instance()
{
static B instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
static C& C::instance()
{
static C instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
我想分解这个 ::instance 方法,但考虑到它使用虚拟方法::load,我无法在A类中定义它。 从理论上讲,我知道这很奇怪,因为类 A 应该有 0 个实例,而 B、C 应该有 1 个实例,但这段代码应该被分解也是有道理的。
你会如何解决这个问题?
I have an abstract class:
class A
{
public:
bool loaded_;
virtual int load() = 0;
}
And several derived classes :
class B:public A
{
public:
int load();
static B& instance();
}
class C:public A
{
public:
int load();
static C& instance();
}
The fact is that the code inside ::instance() methods is the same for each class :
static B& B::instance()
{
static B instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
static C& C::instance()
{
static C instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
I would like to factorize this ::instance method, but given that it uses the virtual method ::load, i cannot define it in the class A.
Theoretically, i know it's weird since the class A should have 0 instance and B,C should have 1 instance but it also makes sense that this code should be factorized.
How would you solve that problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使
instance()
成为一个免费的函数模板:然后您可以像这样使用它:
You could make
instance()
a free function template:Then you can use it like this:
这是CRTP的常见用法,在模板中定义创建实例的函数,然后在每种类型中实例化它:
This is a common usage of the CRTP, define the function that creates the instance in the template and then instantiate it in each type: