C ++:对于CRTP,在派生类中定义的类在基类中不可访问 [英] C++: With CRTP, class defined in the derived class is not accessible in the base class

查看:271
本文介绍了C ++:对于CRTP,在派生类中定义的类在基类中不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是(简化的)基类:

Here is the (simplified) base class:

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

这里是派生:

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

是否有任何解决方法可从访问 ThisWontCompile :: Data SharedObject

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?

推荐答案

这实际上是不相关的无障碍和友谊,它与CRTP的使用相关。考虑下面的示例也会出现问题:

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

问题是 ThisWontCompile 它用作 Base 的模板参数的时间,因此它只能用作 Base 中的不完整类型。

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.

有关您特定问题的一些解决方案,请参阅这个问题,特别是Martin的建议使用traits类,它基本上看起来像这样:

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 可以在 Derived Base 中使用。如果 Derived 本身是一个模板,您可以对traits类使用部分特化。

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.

这篇关于C ++:对于CRTP,在派生类中定义的类在基类中不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆