如果基类是通过模板继承的,则在派生构造函数中初始化基类成员

gla*_*des 1 c++ templates derived-class mixins

鉴于我知道我的基类中存在某个成员a,我如何使用模板派生类来引用它?即使我完全符合资格a,它也不起作用:

演示

#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();
}
Run Code Online (Sandbox Code Playgroud)

产量:

<source>:14:11: error: class 'derived<ImplType>' does not have any field named 'a'
   14 |         : a{2}
      |           ^
Run Code Online (Sandbox Code Playgroud)

S.M*_*.M. 5

使用聚合基类初始化

#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();
}
Run Code Online (Sandbox Code Playgroud)

  • 闻起来有 XY 问题。如果派生类限制、硬编码和访问基类的内容,那么这是一个糟糕的设计。您要解决的实际任务是什么? (2认同)