C++: With CRTP, class defined in the derived class is not accessible in the base class

不羁的心 提交于 2019-12-12 08:51:29

问题


Here is the (simplified) base class:

template <class T>
class SharedObject
{
protected:
    QExplicitlySharedDataPointer <typename T::Data> d;
};

And here is the derived:

class ThisWontCompile : public SharedObject <ThisWontCompile>
{
private:
    friend class SharedObject;
    struct Data : public QSharedData
    {
        int id;
    };
};

Is there any workaround to access ThisWontCompile::Data from SharedObject? What exactly can and what exactly cannot be done with the derived object from the base object?


回答1:


This actually isn't related to the accessibility and friendship, it's related to the use of CRTP. Consider the following example that also exhibits the problem:

template <class T>
struct Base
{
    typedef typename T::Data Data;
};

struct ThisWontCompile : public Base<ThisWontCompile>
{
    struct Data { };
};

The problem is that ThisWontCompile is incomplete at the time it is used as a template argument to Base, so it can only be used as an incomplete type in Base.

For a handful of solutions to your specific problem, consult the answers to this other question, especially Martin's recommendation to use a traits class, which would basically look like this:

// Base
template <typename T>
struct BaseTraits;

template <typename T>
struct Base
{
    typedef typename BaseTraits<T>::Data Data;
};

// Derived
struct Derived;

template <>
struct BaseTraits<Derived>
{
    struct Data { };
};

struct Derived : public Base<Derived>
{
};

typename BaseTraits<Derived>::Data can be used in both Derived and in Base. If Derived is itself a template, you can use a partial specialization for the traits class.



来源:https://stackoverflow.com/questions/5534759/c-with-crtp-class-defined-in-the-derived-class-is-not-accessible-in-the-base

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!