有没有办法在没有基类名称和范围解析运算符的情况下引用基类模板的成员变量?
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
任何地方都很乏味?
作为解决方案,您必须使名称value
依赖,以使其对名称查找可见。除了您展示的那个,您还可以:
-
用
using
介绍名称,template<typename T> struct D1: B1<T> { using B1<T>::value; // or move it in method's scope according to your intent D1() { value = 1; // OK. } };
-
以
this->
.template<typename T> struct D1: B1<T> { D1() { this->value = 1; // OK. } };