Lets say I have:
set<int, less<int> > m_intset;
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;
What's the advantage of such a typedef
? Am I using it correctly?
Some advantages to using typedef:
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.
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.
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.
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.
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.
Typedef's are mostly notational convenience, but they do have a bunch of benefits:
I'm sure there are more I'm not thinking of....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With