在 c++ 中转发声明类的公共 typedef
我试图通过使用前向声明并将 #includes 移动到实现文件中来简化一堆头文件“include spaghetti”。 但是,我不断遇到以下情况:
//Foo.h
#include "Bar.h"
class Foo
{
public:
void someMethod(Bar::someType_t &val);
};
//Bar.h
.
.
.
class Bar
{
public:
typedef std::vector<SomeClass> someType_t;
};
我想在尽可能多的情况下删除#include“Bar.h”。 我还看到 Bar.h 中的 typedef 列在 Bar 类之外的情况。 我假设这两种情况都可以用相同的方式解决。
有任何想法吗?
I'm trying to simplify a bunch of header file "include spaghetti" by using forward declarations and moving #includes into the implementation file. However, I keep coming upon the following scenario:
//Foo.h
#include "Bar.h"
class Foo
{
public:
void someMethod(Bar::someType_t &val);
};
//Bar.h
.
.
.
class Bar
{
public:
typedef std::vector<SomeClass> someType_t;
};
I want to remove #include "Bar.h" in as many cases as possible. I also see the situation where the typedef in Bar.h is listed outside of the Bar class. I'm assuming both situations can be addressed in the same manner.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,您没有太多选择,而且没有一个是完美的。
首先,两个明显且不可接受的解决方案:
typedef
这完全违背了使用typedef
的目的。typedef
的文件。更有趣的解决方案:
typedef
时,这可能会导致大量重新编译。typedef
。 有点烦人,但它有效。最后两个就像进行前向声明,但添加了 typedef。 它们减少了文件的相互依赖性,因为您很少修改 typedef 文件。
我想说,在大多数情况下,中央包含最有利于避免麻烦。 请小心。
Unfortunately you don't have many choices and none is perfect.
First, the two obvious and unacceptable solutions:
typedef
which totally defeats the purpose of using atypedef
.typedef
, which you want to avoid.The more interesting solutions:
typedef
s in the same include and include that file. This creates code coupling between the classes though. You ought to do that only with related classes, else you are going to end up with a god include file and this could lead to a lot of recompiling when you add atypedef
to that file.typedef
s in it. Kind of annoying, but it works.Those last two are like doing forward declarations but with added
typedef
s. They reduce file interdependencies since you are rarely modifying the typedef file.I'd say for most situations, the central include has the most benefit for hassle. Just be careful.
只需使用
class Bar;
。 这告诉 C++ 您正在声明定义 Bar 的意图。Just use
class Bar;
. That tells C++ you're declaring your intention to define Bar.