Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract class and static methods

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 ?

like image 339
Guillaume Thomas Avatar asked Dec 22 '25 22:12

Guillaume Thomas


1 Answers

You could make instance() a free function template:

template<class T>
T& instance()
{
  static T instance_;
  if (!instance_.loaded_)
  {
    instance_.load();
    instance_.loaded_=true;
  }
  return instance_;
}

Then you can use it like this:

instance<B>().do_stuff()
like image 119
sth Avatar answered Dec 24 '25 13:12

sth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!