Initialise C++ base class without typing whole base class type twice

Viewed 70

I'm looking for a C++ pattern or technique that avoids some code replication.

I utilize empty base optimisation for some algorithms. When I inherit from a class that has verbose template arguments it is cumbersome to have to enter the same verbose type in the member initializer list and as the base of a class.

A contrived example:

template <uint32_t Port, uint32_t Pin>
class Pin;

-

template <typename T>
struct ActiveHigh;

template <uint32_t Port, uint32_t Pin>
struct ActiveHigh : Pin<Port, Pin> // <-- First entry.
{
    ActiveHigh() : Pin<Port, Pin>{ false } {} // <-- Duplicate entry.
};

I'm writing a C++ linter which has a certain feature which should really utilise empty base optimisation. There are literally thousands of lines of duplicate entries due to this pattern. Does anybody have a pattern that they use to overcome this code smell?

Edit 1

This is what I have so far, but its sort of bad having to write typename on every instantiation.

1 Answers

You can do the following workaround:

template <uint32_t PortT,
          uint32_t PinT,
          typename ActualPin = Pin<PortT, PinT>>
struct ActiveHigh : ActualPin
{
    ActiveHigh() : ActualPin{ false } {}
};
Related