具有完整类型信息的循环依赖项

Circular dependency with full type information

本文关键字:循环 依赖 信息 类型      更新时间:2023-10-16

我有 2 个类,它们都包含在变体中。然后,该变体在两个类中使用。

template <typename T>
struct Deferred
{
    typedef T value_type;
};
template <typename T>
struct DeferredContainer
{
    typedef typename T::value_type value_type;
};
class DictionaryObject;
class MixedArrayObject;
using DictionaryObjectPtr = Deferred < DictionaryObject >; // DeferredContainer<DictionaryObject>
using MixedArrayObjectPtr = Deferred < MixedArrayObject >; // DeferredContainer<MixedArrayObject>
typedef boost::variant <
    MixedArrayObjectPtr,
    DictionaryObjectPtr
> ContainerPtr;
class MixedArrayObject
{
public:
    typedef int value_type;
    inline void SetContainer(ContainerPtr obj) { _container = obj; }
    inline ContainerPtr GetContainer() const { return _container; }
private:
    ContainerPtr _container;
};
class DictionaryObject
{
public:
    typedef float value_type;
    inline void SetContainer(ContainerPtr obj) { _container = obj; }
    inline ContainerPtr GetContainer() const { return _container; }
private:
    ContainerPtr _container;
};

我不知道这是如何工作的,但是当我尝试通过 typedef 在数组或字典上公开某些属性(并在 DeferredContainer 中使用它们)时,我收到错误:

错误 C2602:"延迟容器::value_type"不是"延迟容器"基类的成员

我可以以某种方式完成这项工作吗?还有其他想法吗?


更新 31.5,下午 4:09。

我已经将问题减少到最低限度。希望这最终引起注意。代码。

将 MixedArrayObjectPtr 切换为 DeferredContainer 后,代码将不再编译。

我建议重新排序您的代码,以确保所有定义都按照它们的使用顺序排列。由于需要variant具有完整的类型,因此我们必须使用 Object* 而不是 Object

// main types
class Dictionary;
class Array;
template <typename T> struct DeferredContainer;
using DictionaryPtr = DeferredContainer<Dictionary>;
using ArrayPtr = DeferredContainer<Array>;
struct Object;
// now definitions of them
class Dictionary
{
public:
     typedef int value_type;
     std::map<Name, Object*> list; // note Object*
};
class Array
{
public:
     typedef int value_type;
     std::vector<Object*> list; // note only one type here
};
template <typename T>
struct DeferredContainer
{
    // now can do stuff with T::value_type
};

毕竟,我们可以宣布Object.不幸的是,我们不能转发声明别名,但我们可以只包装variant

struct Object {
    boost::variant<
        DictionaryPtr,
        ArrayPtr
    > value;
};

通过这种排序,一切都可以编译。