【问题标题】:how to declare class template in header file (due of circular dependencies)如何在头文件中声明类模板(由于循环依赖)
【发布时间】:2019-03-09 16:14:13
【问题描述】:

拥有

Bar.h

template<class T>
class Bar<T> {
//...
}

Foo.h

template<T>
class Bar<T>;
//#include "Bar.h" removed due of circular dependencies, I include it in .cpp file

template<class T>
class Foo {
...
private:
    Bar<T> *_bar;
}

如您所见,我需要包含 bar.h,但由于循环依赖的原因,我不能在我的项目中这样做..

就像我通常做的那样,我只是在 .h 中编写定义,在 .cpp 中编写实现 但是我对这个例子有一些问题,因为我不知道带模板的类的语法..

这有什么语法吗? 我在当前示例中收到以下编译器错误:

Bar is not a class template

【问题讨论】:

  • 类模板需要完全存在,不幸的是。还要准备一份 SSCCE。
  • 我已经编辑了我的问题*
  • 好的,所以我必须重新设计我的应用程序>
  • 我的两个循环类依赖项都在使用模板,所以我无法更改使用定义的类 + 包含在 .cpp 中:/
  • 您错误地定义了您的模板,并且您也错误地声明了它。试试template&lt;typename T&gt; class Bar {};template&lt;typename T&gt; class Bar;分别作为定义和前向声明。 P.S 模板的定义必须存在于每个翻译单元中。

标签: c++ templates circular-dependency


【解决方案1】:

前向声明语法是

template<T> class Bar;

所以你的代码变成了:

Foo.h

template<T> class Bar;

template<class T>
class Foo {
...
private:
    Bar<T> *_bar;
};

#include "Foo.inl"

Foo.inl

#include "bar.h"

// Foo implementation ...

Bar.h

template<class T>
class Bar<T> {
//...
};

【讨论】:

    【解决方案2】:

    您的示例没有循环依赖。 Bar 不依赖于 Foo 以任何方式。您可以按以下顺序定义模板:

    template<class T> class Bar {};
    
    template<class T>
    class Foo {
    private:
        Bar<T> *_bar;
    };
    

    如果您希望将定义分成两个文件,您可以像这样实现上述排序:

    // bar:
    template<class T>
    class Bar {};
    
    // foo:
    #include "bar"
    
    template<class T>
    class Foo {
    private:
        Bar<T> *_bar;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多