解决模板类之间的循环依赖关系

时间:2010-07-28 14:24:02

标签: c++ templates circular-dependency

我有两个类Foo<T>Bar<T>,派生自Base。每个方法都会覆盖方法virtual Base* convert(ID) const,其中ID是唯一标识FooBar的特定实例的类型实例(假装它是enum) 。问题是Foo::convert()需要能够返回Bar个实例,同样Bar::convert()需要能够实例化Foo。由于它们都是模板,因此导致Foo.hBar.h之间存在循环依赖关系。我该如何解决这个问题?

编辑:前向声明不起作用,因为每个方法的实现都需要另一个类的构造函数:

Foo.h

#include <Base.h>

template<class T> class Bar;

template<class T>
class Foo : public Base { ... };

template<class T>
Base* Foo<T>::convert(ID id) const {

    if (id == BAR_INT)
        return new Bar<int>(value); // Error.

    ...

}

Bar.h

#include <Base.h>

template<class T> class Foo;

template<class T>
class Bar : public Base { ... };

template<class T>
Base* Bar<T>::convert(ID id) const {

    if (id == FOO_FLOAT)
        return new Foo<float>(value); // Error.

    ...

}

错误自然是“无效使用不完整类型”。

4 个答案:

答案 0 :(得分:21)

您需要做的是将类声明与实现分开。像

这样的东西
template <class T> class Foo : public Base
{
    public:
    Base* convert(ID) const;
}

template <class T> class Bar : public Base
{
    public:
    Base* convert(ID) const;
}

template <class T> Base* Foo<T>::convert(ID) const {return new Bar<T>;}
template <class T> Base* Bar<T>::convert(ID) const {return new Foo<T>;}

这样,在定义函数时就有了完整的类定义。

答案 1 :(得分:12)

您应该在标题

中使用模板类前向声明
template <class T>
class X;

是非常好的模板类前向声明​​。

答案 2 :(得分:11)

(更新) 您应该能够处理与非模板类相同的操作。像这样写你的Bar.h. (同样对于Foo.h)

#if !defined(BAR_H_INCLUDED)
#define BAR_H_INCLUDED

template <class T>
class Foo;

template <class T>
class Bar
{
    /// Declarations, no implementations.
}    

#include "Foo.h"

template <class T>
Base* Bar<T>::Convert() {  /* implementation here... */ }
#endif

答案 3 :(得分:8)

James Curran的回答是天赐之物。一般来说,James的想法是限制所需头文件的包含,直到需要来自包含头文件的成员('声明)为止。举个例子:

t1.hh

#ifndef S_SIGNATURE
#define S_SIGNATURE

struct G; // forward declaration

template<typename T>
struct S {
  void s_method(G &);
};

#include "t2.hh" // now we only need G's member declarations

template<typename T>
void S<T>::s_method(G&g) { g.g_method(*this); }

#endif

t2.hh

#ifndef G_SIGNATURE
#define G_SIGNATURE

template<typename T>
struct S; // forward declaration

struct G {
  template<typename T>
  void g_method(S<T>&);
};

#include "t1.hh" // now we only need S' member declarations

template<typename T>
void G::g_method(S<T>& s) { s.s_method(*this); }

#endif

t.cc

#include "t1.hh"
#include "t2.hh"

S<int> s;
G g;

int main(int argc,char**argv) {
  g.g_method(s); // instantiation of G::g_method<int>(S<int>&)
}
相关问题