引用基类模板成员变量的简单方法。

问题描述 投票:0回答:2

有没有办法不用基类名和作用域解析运算符来引用基类模板的成员变量?

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++ base-class class-template
2个回答
5
投票

作为解决方法,你必须把名字做成 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.
        }
    };
    
© www.soinside.com 2019 - 2024. All rights reserved.