C++:使用 CRTP,派生类中定义的类在基类中不可访问

标签 c++ qt templates crtp

这是(简化的)基类:

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

是否有从 SharedObject 访问 ThisWontCompile::Data 的解决方法?从基础对象派生的对象到底能做什么,不能做什么?

最佳答案

这实际上与可访问性和友元无关,它与CRTP的使用有关。请考虑以下也存在问题的示例:

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

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

问题是 ThisWontCompile在用作 Base 的模板参数时不完整, 所以它只能作为 Base 中的不完整类型使用.

有关您的特定问题的一些解决方案,请参阅 this other question 的答案。 ,尤其是 Martin 关于使用 traits 类的建议,它基本上看起来像这样:

// 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可同时用于 DerivedBase .如果Derived本身就是一个模板,您可以对特征类使用部分特化。

关于C++:使用 CRTP,派生类中定义的类在基类中不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5534759/

相关文章:

c++ - 在 Qt 应用程序中单击按钮时在外部浏览器上打开 url

c++ - opencv加载和显示图像

python - PyQt4 - 拖放

.net - 自动卡住从模板构建的 wpf 对象

c++ - 将 Eigen::TensorMap 转换为 Eigen::Tensor

c++ - 从我在 C++ 中不拥有的应用程序读取内存(vb.net 中的示例)

c++ - 我可以在 Qt 中的继承类的初始化中放置什么

qt - 一个插槽的多个信号

css - 将 CSS 添加到 Joomla 3 模板管理区域

c++ - 命名空间模板函数和隐藏的命名空间变量