Home > database >  Public class member not visible when CRTP derived type is a template class
Public class member not visible when CRTP derived type is a template class

Time:09-17

The below code doesn't compile.

I want Derived<T> to access m_vec member of Base. However, because Derived<T> is templated, it implemented CRTP via : public Base<Derived<T>> and m_vec is not visible.

If I change Derived<T> to just Derived, m_vec becomes visible.

Why is this/is there a workaround?

#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;
}

CodePudding user response:

Access the member using

this->m_vec.clear();

That should compile.

  • Related