在 c++ 中转发声明类的公共 typedef

发布于 2024-07-18 20:00:24 字数 410 浏览 11 评论 0原文

我试图通过使用前向声明并将 #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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧瑾黎汐 2024-07-25 20:00:24

不幸的是,您没有太多选择,而且没有一个是完美的。

首先,两个明显且不可接受的解决方案:

  • 您可以转发声明 typedef 这完全违背了使用 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:

  • You can forward declare the typedef which totally defeats the purpose of using a typedef.
  • You include the file which contains the typedef, which you want to avoid.

The more interesting solutions:

  • Have all related typedefs 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 a typedef to that file.
  • For each class, have a separate include with the typedefs in it. Kind of annoying, but it works.

Those last two are like doing forward declarations but with added typedefs. 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.

长安忆 2024-07-25 20:00:24

只需使用class Bar;。 这告诉 C++ 您正在声明定义 Bar 的意图。

Just use class Bar;. That tells C++ you're declaring your intention to define Bar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文