Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Access the member using

this->m_vec.clear();

That should compile.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading