抽象类和静态方法
abstract class and static methods
我有一个抽象类:
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_;
}
我想分解this::instance方法,但是考虑到它使用虚拟方法::load,我不能在类A中定义它。从理论上讲,我知道这很奇怪,因为类A应该有0个实例,B,C应该有1个实例,但这段代码应该被分解也是有意义的。
你怎么解决这个问题?
你可以让instance()
成为一个自由的函数模板:
template<class T>
T& instance()
{
static T instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
那么你可以这样使用:
instance<B>().do_stuff()
这是CRTP的一种常见用法,定义在模板中创建实例的函数,然后在每种类型中实例化它:
struct A {
virtual ~A() {} // don't forget to make your destructor virtual!
virtual void load() = 0;
};
template <typename T>
struct instance_provider {
static T& instance() { /* implementation */ }
};
struct B : A, instance_provider<B> {
virtual void load();
};
struct C : A, instance_provider<C> {
virtual void load();
};
相关文章:
- 调用从模板派生的类的静态方法,而不指定模板
- 对纯抽象类中方法的未定义引用
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 用c++中的纯虚拟方法抽象模板类
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 在子类上调用模板化静态方法时获取类的类型名
- 仅具有公共静态方法的帮助程序类
- 抽象类/接口中的空方法是否被认为是一种好的做法?
- 静态方法返回类的shared_ptr
- 静态方法与类中的本地方法
- 在C++的静态方法中将类名作为字符串获取
- Boost::p ython 静态方法返回类的实例
- C++具有静态方法的类的模板
- 纯抽象类可以包含静态常量、静态方法或非虚析构函数吗?
- 具有静态方法的类或具有普通方法的类
- c++中只有静态方法的类的优点
- 从静态方法获取类的类型
- 是否可以获得调用静态方法的类
- 抽象类和静态方法