Initialize base class member in derived constructor if base is inherited via template

72 Views Asked by At

Given I know that a certain member a exists in my base class, how can I refer to it using my template-derived class? Even if I fully qualify a, it doesn't work:

Demo

#include <iostream>
#include <string_view>
#include <memory>
#include <string>

struct base {
    int a;
};

template <typename ImplType>
struct derived : public ImplType {

    derived()
        : a{2}
    {}

    auto print() {
        std::cout << ImplType::a << std::endl;
    }
};

int main() {
    derived<base> d{};
    d.print();
}

Yields:

<source>:14:11: error: class 'derived<ImplType>' does not have any field named 'a'
   14 |         : a{2}
      |           ^
1

There are 1 best solutions below

6
273K On

Use the aggregate base class initialization

#include <iostream>

struct base {
    int a;
};

template <typename ImplType>
struct derived : public ImplType {
    derived()
        : ImplType{2}
    {}

    auto print() {
        std::cout << ImplType::a << std::endl;
    }
};

int main() {
    derived<base> d{};
    d.print();
}