两个模板类,其中的方法相互调用
Two template classes with methods calling each other
两个模板类有两个方法,每个方法调用另一个类的方法:
// 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.h
和Bar.h
。为了能够使用Bar
,您还需要Foo.h
和Bar.h
.最好将它们放在一个 .h 文件中。
- 定义类。
- 最后实现成员函数。
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++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用