两个模板类,其中的方法相互调用

Two template classes with methods calling each other

本文关键字:方法 调用 两个      更新时间:2023-10-16

两个模板类有两个方法,每个方法调用另一个类的方法:

// Foo.h
template<typename T>
class Foo {
public:
static void call_bar() {
Bar<int>::method();
}
static void method() {
// some code
}
};
// Bar.h
template<typename T>
class Bar {
public:
static void call_foo() {
Foo<int>::method();
}
static void method() {
// some code
}
};

我怎样才能让它工作?简单地将#include "Bar.h"添加到 Foo.h(反之亦然(是行不通的,因为每个类都需要另一个类。

编辑:我也尝试了前向声明,但它在链接阶段仍然失败:

// Bar.h
template <typename T>
class Foo {
public:
static void method();
};
// Foo.h
template <typename T>
class Bar {
public:
static void method();
};

当您有两个相互依赖的类模板时,使用两个 .h 文件没有意义。为了能够使用Foo,您需要Foo.hBar.h。为了能够使用Bar,您还需要Foo.hBar.h.最好将它们放在一个 .h 文件中。

  1. 定义类。
  2. 最后实现成员函数。

FooBar.h:

template<typename T>
class Foo {
public:
static void call_bar();
static void method() {
// some code
}
};
template<typename T>
class Bar {
public:
static void call_foo();
static void method() {
// some code
}
};
template<typename T>
void Foo<T>::call_bar() {
Bar<int>::method();
}
template<typename T>
void Bar<T>::call_foo() {
Foo<int>::method();
}