引用基本 class 模板成员变量的简单方法

Simple way to reference member variables of base class templates

有什么方法可以在没有基本 class 名称和范围解析运算符的情况下引用基本 class 模板的成员变量?

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 从属,以使其在名称查找中可见。除了您展示的,您还可以:

  1. 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.
        }
    };
    
  2. 符合条件this->

    template<typename T>
    struct D1: B1<T> {
        D1() {
            this->value = 1;  // OK.
        }
    };