cha*_*ink 2 c++ templates base-class class-template name-lookup
有没有办法在没有基类名称和范围解析运算符的情况下引用基类模板的成员变量?
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有可能不写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.
}
};
Run Code Online (Sandbox Code Playgroud)符合资格this->。
template<typename T>
struct D1: B1<T> {
D1() {
this->value = 1; // OK.
}
};
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |