简体   繁体   English

Forward在c ++中声明一个类的public typedef

[英]Forward declare a class's public typedef in c++

I'm trying to simplify a bunch of header file "include spaghetti" by using forward declarations and moving #includes into the implementation file. 我正在尝试通过使用前向声明并将#includes移动到实现文件中来简化一堆头文件“include spaghetti”。 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. 我希望在尽可能多的情况下删除#include“Bar.h”。 I also see the situation where the typedef in Bar.h is listed outside of the Bar class. 我还看到Bar.h中的typedef列在Bar类之外的情况。 I'm assuming both situations can be addressed in the same manner. 我假设两种情况都可以用同样的方式解决。

Any ideas? 有任何想法吗?

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 . 你可以转发声明typedef ,这完全违背了使用typedef的目的。
  • You include the file which contains the typedef , which you want to avoid. 您包含要包含typedef的文件,您要避免使用该文件。

The more interesting solutions: 更有趣的解决方案:

  • Have all related typedef s in the same include and include that file. 将所有相关的typedef包含在内并包含该文件。 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. 你应该只用相关的类来做到这一点,否则你将最终得到一个神包含文件,当你向该文件添加一个typedef时,这可能会导致大量的重新编译。
  • For each class, have a separate include with the typedef s in it. 对于每个类,都有一个单独的include,其中包含typedef Kind of annoying, but it works. 有点讨厌,但它的确有效。

Those last two are like doing forward declarations but with added typedef s. 最后两个就像做前向声明但添加了typedef They reduce file interdependencies since you are rarely modifying the typedef file. 它们减少了文件的相互依赖性,因为您很少修改typedef文件。

I'd say for most situations, the central include has the most benefit for hassle. 我会说在大多数情况下,中心包含的麻烦最有利。 Just be careful. 小心点

Just use class Bar; 只需使用class Bar; . That tells C++ you're declaring your intention to define Bar. 这告诉C ++你宣布你有意定义Bar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM