Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate virtuality for method template

I have a class hierarchy where I want to introduce a method template that would behave like if it was virtual. For example a simple hierarchy:

class A {
  virtual ~A() {}

  template<typename T>
  void method(T &t) {}
};

class B : public A {
  template<typename T>
  void method(T &t) {}
};

Then I create object B:

A *a = new B();

I know I can get the type stored in a by typeid(a). How can I call the correct B::method dynamically when I know the type? I could probably have a condition like:

if(typeid(*a)==typeid(B))
    static_cast<B*>(a)->method(params);

But I would like to avoid having conditions like that. I was thinking about creating a std::map with typeid as a key, but what would I put as a value?

like image 483
Juraj Blaho Avatar asked Jan 18 '23 14:01

Juraj Blaho


2 Answers

You can use the "Curiously Recurring Template Pattern" http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

Using this pattern, the base class takes the derived class type as a template parameter, meaning that the base class can cast itself to the derived type in order to call functions in the derived class. It's a sort of compile time implementation of virtual functions, with the added benefit of not having to do a virtual function call.

template<typename DERIVED_TYPE>
class A {
public:
    virtual ~A() {}

    template<typename T>
    void method(T &t) { static_cast<DERIVED_TYPE &>(*this).methodImpl<T>(t); }
};

class B : public A<B>
{
friend class A<B>;

public:
    virtual ~B() {}

private:
    template<typename T>
    void methodImpl(T &t) {}
};

It can then be used like this...

int one = 1;
A<B> *a = new B();
a->method(one);
like image 135
Alan Avatar answered Jan 27 '23 11:01

Alan


Is there any common code you could extract and make virtual?

class A {
  virtual ~A() {}

  template<typename T>
  void method(T &t) 
  {
      ...
      DoSomeWork();
      ...
  }

  virtual void DoSomeWork() {}
};

class B : public A {
  virtual void DoSomeWork() {}
};
like image 39
DanDan Avatar answered Jan 27 '23 10:01

DanDan