代码之家  ›  专栏  ›  技术社区  ›  intrigued_66

当CRTP派生类型是模板类时,公共类成员不可见

  •  1
  • intrigued_66  · 技术社区  · 3 年前

    以下代码未编译。

    我想要 Derived<T> 访问 m_vec 的成员 Base 。但是,因为 派生<T> 是模板化的,它通过 : public Base<Derived<T>> m_vec 不可见。

    如果我改变 派生<T> 只是 Derived , m_vec 变得可见。

    为什么会这样/有变通办法吗?

    #include <vector>
    
    template<class SUB_CLASS>
    struct Base
    {
        Base(int config){}
        std::vector<std::string> m_vec;  
    };
    
    template<class T>
    struct Derived : public Base<Derived<T>>
    {
        Derived(int config) : Base<Derived<T>>(config){}
        
        void start()
        {
            m_vec.clear();   // This line doesn't compile. m_vec is not accessible
        }
    };
    
    int main()
    {
        int config = 0;
        Derived<int> d(config);
        d.start();
        return 0;
    }
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   JustLearning    3 年前

    使用访问成员

    this->m_vec.clear();
    

    应该编译。