[英]Circular dependency in template class
I have a circular dependency simplified to the following: 我将循环依赖简化为以下内容:
// Bar.h
struct Bar {};
// Base.h
#include "Foo.h"
struct Bar;
struct Base {
void func(std::shared_ptr<Foo<Bar>> foobar); // use methods of Foo in some way.
};
// Derived.h
#include "Base.h"
struct Derived : public Base {};
// Foo.h
#include "Derived.h"
template <typename T>
struct Foo {
void func(std::shared_ptr<Derived> d) {
// use methods of Derived in some way.
}
};
I can't simply forward declare Foo
in Base.h
as it is a template class, can't forward declare Base
in Derived.h
due to the polymorphism, and can't forward declare Derived
in Foo.h
because Foo::func
uses members of Derived
. 我不能简单地向前声明
Foo
在Base.h
,因为它是一个模板类,不能转发申报Base
中Derived.h
由于多态性,并且不能向前申报Derived
在Foo.h
,因为Foo::func
使用Derived
成员。
I've read before about separating template implementation from the declaration thought I'm unaware of best practices and unsure if it would work in this case. 我之前已经读过有关将模板实现与声明分开的想法,因为我不了解最佳实践,也不确定在这种情况下是否可以使用。 The two,
Derived
and Foo
are used widely throughout my program. 在我的程序中,
Derived
和Foo
这两个被广泛使用。
How can I resolve this dependency? 如何解决这种依赖性?
Declaring a function taking a std::shared_ptr<type>
doesn't require a full definition of type
, all that is needed is a (forward) declaration. 声明一个带有
std::shared_ptr<type>
函数并不需要完整的type
定义,所需要的只是一个(forward)声明。 This allows you to avoid #include
of Derived.h (in Foo.h) and/or of Foo.h (in Base.h) 这使您可以避免
#include
的Derived.h(在Foo.h中)和/或Foo.h(在Base.h中)
Enable inline functions in classes referencing each other: 在相互引用的类中启用内联函数:
header Ah 标头Ah
struct B;
struct A {
void a() {}
void f();
std::shared_ptr<B> b;
};
#include "A.tcc"
header A.tcc 标头A.tcc
#include B.h
inline void A::f() { b->b(); }
header Bh 标头Bh
struct A;
struct B {
void b() {}
void f();
std::shared_ptr<A> a;
};
#include "B.tcc"
header B.tcc 标头B.tcc
#include A.h
inline void B::f() { a->a(); }
Please ensure all files have header guards! 请确保所有文件都有标题保护!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.