c++ - 模板、循环依赖、方法,天哪!

标签 c++ templates circular-dependency

背景:我正在研究 framework它基于现有的 Java 类模型生成 C++ 代码。因此,我无法更改下面提到的循环依赖。

给定:

  • 父子类关系
  • 父级包含子级列表
  • 用户必须能够在运行时查找列表元素类型

我在以下测试用例中对此进行了建模:

main.cpp

#include "Parent.h"

#include <iostream>
using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
    Parent parent;
    cout << Parent::getType() << endl;
    cout << parent.getChildren().getType() << endl;
    return 0;
}

父类.h

#ifndef PARENT_H
#define PARENT_H

#include <string>

#include "Array.h"
class Child;

class Parent
{
public:
    Array<Child> getChildren()
    {
        return Array<Child>();
    }

    static std::string getType()
    {
        return "parent";
    }
};

#endif

child .h

#ifndef CHILD_H
#define CHILD_H

#include "Parent.h"

class Child: public Parent
{
};

#endif

数组.h

template <typename ElementType>
class Array
{
public:
    static std::string getType()
    {
        return ElementType::getType();
    }
};
  1. 当我编译上面的代码时,我得到: error C2027: use of undefined type 'Child'return ElementType::getType();

  2. 如果我尝试 #include "Child.h"我得到的不是前向声明: error C2504: 'Parent' : base class undefinedclass Child: public Parent

  3. 如果我尝试 Array<Child*>而不是 Array<Child>我得到: error C2825: 'ElementType': must be a class or namespace when followed by '::'return ElementType::getType();

循环依赖的产生是因为:

  1. Child.h 需要了解 Parent 类
  2. Parent.h 需要了解 Array 类
  3. Array.h 需要了解 Child 类

有什么想法吗?

最佳答案

错误是由于在实例化模板时不存在子类。

将以下内容添加到 Main 或 Parent.h 的末尾:

#include "Child.h"

这在 g++ 4 和 VS 2010 上都能很好地编译。

关于c++ - 模板、循环依赖、方法,天哪!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177227/

相关文章:

c++ - 模板中的函数指针

c++ - 具有指向派生对象 : How to tell both of each other's existence? 的指针的基类

c++ - 通过函数转发 const 引用

c++ - c++ 中 typedef 和模板的常量引用

c++ - 基于方法的特化模板

c++ - 为什么 C++ 不能推断模板类型?

java - 模块java类之间的循环依赖

java - 如何解决JAR之间的循环依赖?

c++ - 在非类成员函数的参数中传递类成员函数

c++ - libvlc_video_set_subtitle_file 不工作