【发布时间】:2020-09-19 11:58:23
【问题描述】:
没有基类名和作用域解析运算符,有没有办法引用基类模板的成员变量?
template<typename D>
struct B0 {
int value;
};
struct D0: B0<D0> {
D0() {
B0<D0>::value = 1; // OK.
value = 1; // OK without `B0<D0>::`.
}
};
template<typename T>
struct B1 {
T value;
};
template<typename T>
struct D1: B1<T> {
D1() {
B1<T>::value = 1; // OK.
// value = 1; // Compile error without `B1<T>::`.
// Compile error: use of undeclared identifier 'value'
// `B1<T>::` is tedious everywhere `value` is referenced.
}
};
template<typename T, typename D>
struct B2 {
T value;
};
template<typename T>
struct D2: B2<T, D2<T>> { // CRTP
D2() {
B2<T, D2<T>>::value = 1; // OK.
// value = 1; // Compile error without `B2<T, D2<T>>::`.
// Compile error: use of undeclared identifier 'value'
// `B2<T, D2<T>>::` is more tedious for CRTP.
}
};
int main() {
return 0;
}
是否可以不写B1<T>:: 或B2<T, D2<T>>::,这在任何地方引用value 都很乏味?
【问题讨论】:
标签: c++ templates base-class name-lookup class-template