问题描述
我发现自己最近经常做的事是声明typedef与该类中的特定类相关,即
Something I have found myself doing often lately is declaring typedefs relevant to a particular class inside that class, i.e.
class Lorem
{
typedef boost::shared_ptr<Lorem> ptr;
typedef std::vector<Lorem::ptr> vector;
//
// ...
//
};
这些类型在代码中的其他位置使用:
These types are then used elsewhere in the code:
Lorem::vector lorems;
Lorem::ptr lorem( new Lorem() );
lorems.push_back( lorem );
我喜欢的原因:
- 它减少类模板引入的噪声,
std :: vector< Lorem>
变成Lorem :: vector
等。 - 它作为意图声明 - 在上面的示例中,Lorem类旨在通过
boost :: shared_ptr
并存储在向量中。 - 它允许实现更改 - 即如果Lorem需要更改为intrusively引用计数
- 我认为它看起来更漂亮,可以说更容易一些
- It reduces the noise introduced by the class templates,
std::vector<Lorem>
becomesLorem::vector
, etc. - It serves as a statement of intent - in the example above, the Lorem class is intended to be reference counted via
boost::shared_ptr
and stored in a vector. - It allows the implementation to change - i.e. if Lorem needed to be changed to be intrusively reference counted (via
boost::intrusive_ptr
) at a later stage then this would have minimal impact to the code. - I think it looks 'prettier' and is arguably easier to read.
我不喜欢的原因:
- 有些依赖关系的问题 - 如果你想在另一个类中嵌入一个
Lorem :: vector
,但只需要向前声明Lorem(而不是引入一个依赖于其头文件),那么你最终不得不使用显式类型(例如boost :: shared_ptr< Lorem>
而不是Lorem :: ptr
),这有点不一致。 >
- 这可能不是很常见,因此更难理解?
- There are sometimes issues with dependencies - if you want to embed, say, a
Lorem::vector
within another class but only need (or want) to forward declare Lorem (as opposed to introducing a dependency on its header file) then you end up having to use the explicit types (e.g.boost::shared_ptr<Lorem>
rather thanLorem::ptr
), which is a little inconsistent. - It may not be very common, and hence harder to understand?
我的编码风格,所以它会是好的,以获得一些其他意见,所以我可以剖析我的想法一点点。
I try to be objective with my coding style, so it would be good to get some other opinions on it so I can dissect my thinking a little bit.
推荐答案
我认为它是优秀的风格,我自己使用它。最好尽可能地限制名称的范围,并且使用类是在C ++中执行此操作的最佳方法。例如,C ++标准库大量使用类中的typedef。
I think it is excellent style, and I use it myself. It is always best to limit the scope of names as much as possible, and use of classes is the best way to do this in C++. For example, the C++ Standard library makes heavy use of typedefs within classes.
这篇关于C ++中的内部typedefs - 好的风格还是坏的风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!