为什么我应该在 C++ 中使用 typedef? [英] Why should I use typedefs in C++?

查看:30
本文介绍了为什么我应该在 C++ 中使用 typedef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

set<int, less<int> > m_intset;

那行得通,但现在我将其更改为 typedef,最终得到两行代码:

That works, but now I change it to typedef, and I do end up with two lines of code:

typedef set<int, less<int> > SetInt;
SetInt m_intset;

这样的 typedef 有什么好处?我是否正确使用它?

What's the advantage of such a typedef? Am I using it correctly?

推荐答案

使用 typedef 的一些优势:

  1. 简化:现在,每次您通常都需要 set>,你只需要输入 SetInt.如果您只使用一次集合,这没什么大不了的,但是如果您有同一个集合的多个实例,或者需要访问其迭代器,则较短的形式更易于阅读和输入.

  1. Simplification: Now, every time you would normally have needed set<int, less<int> >, you only have to type SetInt. Not a big deal if you're only using the set once, but if you've got multiple instances of the same set, or need to access iterators thereof, the shorter form is much easier to read and type.

澄清:set> 没有告诉我任何关于变量的用途,只是它是一组整数.使用 typedef,您可以选择解释类型用途的标识符,例如 InventoryCoordinates,例如.

Clarification: set<int, less<int> > doesn't tell me anything about what the variable is used for, just that it's a set of ints. With typedef, you can choose an identifier that explains the purpose of the type, such as Inventory or Coordinates, for example.

抽象:程序变化.尽管您可能认为您需要一个 set> 现在,您的需求在未来总是有可能发生变化,因此需要 set>vector 或其他一些更改.通过使用typedef,您只需在一个地方解决这个问题,它会影响程序中的每个SetInt 实例.这比手动更改源文件中的十几个或更多条目要简单得多,也更不容易出错.

Abstraction: Programs change. Although you may think you need a set<int, less<int> > now, there's always the possibility that your requirements may change in the future, necessitating a set<unsigned long, less<unsigned long> > or vector<int> or some other change. By using a typedef, you would only have to fix this in one place, and it will affect every instance of SetInt in the program. This is far simpler and less prone to error than manually changing a dozen or more entries in the source files.

由于上面的第 2 和第 3 点,typedef 在类或库中使用时可以非常强大,因为它可以加强接口和实现之间的分离,这通常被认为是良好的 C++ 形式.

Due to points 2 and 3 above, typedef can be very powerful when used inside a class or a library, since it can strengthen the separation between interface and implementation which is generally considered good C++ form.

当然,大多数这些优势只有在您在同一个程序中多次使用同一种类型时才能真正体现出来.如果您只希望使用 set<int,less<int>> 一次,typedef 可能是矫枉过正.

Of course, most of these advantages only really show themselves if you're using the same type multiple times in the same program. If you only expect to use the set<int, less<int> > once, typedef is probably overkill.

这篇关于为什么我应该在 C++ 中使用 typedef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆