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)
使用聚合基类初始化
#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)