Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use typedefs in C++?

Tags:

c++

typedef

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?

like image 393
Tom Avatar asked Nov 28 '22 05:11

Tom


2 Answers

Some advantages to using typedef:

  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.

  2. 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.

  3. 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.

like image 150
goldPseudo Avatar answered Dec 05 '22 09:12

goldPseudo


Typedef's are mostly notational convenience, but they do have a bunch of benefits:

  • Declaring function pointer types (e.g. for callbacks)--notoriously hard to get right when spelled out completely.
  • Dependent type information is easier to describe (e.g. SetInt::iterator) and should you ever change your mind (suppose you went to a hash_set instead of a std::set), is effectively updated immediately due to the typedef
  • They describe intent better than built-in typenames do (e.g. typedef int ErrCode)

I'm sure there are more I'm not thinking of....

like image 37
Drew Hall Avatar answered Dec 05 '22 09:12

Drew Hall