这是(简化的)基类:
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
可同时用于 Derived
在Base
.如果Derived
本身就是一个模板,您可以对特征类使用部分特化。
关于C++:使用 CRTP,派生类中定义的类在基类中不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5534759/