Home > Net >  simplify using base template class statement
simplify using base template class statement

Time:05-20

Often in derived template classes I need to refer to the base to access members. I end up writing code like this:

template<typename A>
struct BaseClass
{
};

template<typename B>
struct Derived : public BaseClass<int>
{
  using Base = BaseClass<int>;
};

This gets more verbose and harder to maintain for a large number of classes with a lot of template arguments.

Is there a cleaner way to import base symbols in this case?

CodePudding user response:

If Derived is not itself a template class: You can simply use BaseClass (the inherited injected-class-name):

struct Derived : public BaseClass<int>
{
  void f()
  {
    BaseClass::f();
  }
};

If it is also a template, using Base = BaseClass<int>; is probably the best way.

CodePudding user response:

I think you can do things the other way i.e. defer the base resolution to the base class instead, so that it would be automatically resolved for any new derived class without bothering of rewriting it for each one.

Something like:

template <typename A>
struct BaseClass
{
    using Base = BaseClass<A>;
};

template <typename B>
struct Derived : public BaseClass<int>
{};

Live example

  • Related