typedef 向前声明_向前声明一个类的公共typedef在c ++

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 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?

解决方案

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 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 situation, the central include has the most benefit for hassle. Just be careful.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值