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

j13ufse2  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(173)

如果我知道某个成员a存在于我的基类中,我如何使用模板派生类引用它?即使我完全限定a,它也不起作用:
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();
}

产量:

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

nr7wwzry1#

使用聚合基类初始化

#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();
}

相关问题