gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:21:47 25 4
gpt4 key购买 nike

这是(简化的)基类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com