c++ - 两个模板类,其方法相互调用

标签 c++ templates

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

// 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();
}

关于c++ - 两个模板类,其方法相互调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689555/

相关文章:

amazon-web-services - 使用 for 和 escape 最后一个逗号进行地形改造模板文件

c++ - 在一些容器中处理一个对象

templates - 在 Jekyll 模板中定义 site.title

C++和const reference to temporary binding问题(在C++0X中实现D语言传值传引用规则)

c++ - 是否可以通过 lambda 将变量模板传递给函数?

c++ - 可以采用 lambda 或函数指针并推断参数以传递给另一个模板的模板函数

c++ - 2 个数组/图像相乘的多线程性能 - Intel IPP

c++ - 诠释 x;整数y;诠释*ptr;不是初始化吧?

c++ - 删除 boost::interprocess::named_mutex 的问题

c++ - 如何在属性表中捕获 "tab changed"事件