@ wrote... (10 years, 6 months ago)

Part of my Why is simple hard? series.

Do you even typedef bro?

A typedef makes an alias from one defined type into another. This is extraordinarily handy if you want to be able to read or modify your code in the future.

Consider this:

int some_function();
int some_other_function();
void print_err_msg( int ec );
// vs
typedef int err_code;
err_code some_function();
err_code some_other_function();
void print_err_msg( err_code ec );

I think it's significantly more obvious what the author was trying to accomplish. Then, if you ever need to be a little more explicit, you can do the following and then let the compiler help you out:

// delete typedef
enum err_code { err_success, err_no_memory, err_not_a_file, ... };

But before we get started, don't do this:

typedef struct _MyStruct {
int a;
} MyStruct;

I see this so often I thought that the original coders knew something I didn't. But no amount of Google'ing can tell me why you do that over this:

struct MyStruct {
int a;

I suspect this is some carry-over from C but if there actually is a reason to do this in C++ then please let me know in the comments.

But anyhow, typdefs. I see this all the time:

class Foo {
std::vector<int> my_ints;
for( std::vector<int>::iterator i = my_ints.begin(); ... )

How about:

class Foo {
typedef std::vector<int> int_coll;
int_coll my_ints;
for( int_coll::iterator iter = my_ints.begin(); ... )

And if your collection type ever needs to change from a std::vector to a std::list or std::map (or whatever) it's a one line change and everything (even those for loops) just works! No need to find every use std::vector and fix things. Plus it's less typing every time.

On that note, do this instead: BOOST_FOREACH( auto element, collection). OMG is that awesome. Or if you're using a C++11 compiler for_each( auto element : collection ) OMG Unicorns!

But what I'm really loving and have just recently seen/learned is this:

class Foo {
  typedef std::shared_ptr<Foo> pointer;
  typedef std::vector<pointer> collection;

If you do that will all your classes then your code starts to become very elegant and predictable:

Foo::pointer foo;
Foo::collection make_some_foo( int num );

So there are a couple of great examples of using typedefs. They're simple, make your code easier to read and easier to maintain. There is zero speed/space/etc tradeoffs. There is zero reasons to not use typdefs.

Bro, I use typedefs.

Category: tech, Tags: cpp, programming, simple
Comments: 0
Click here to add a comment