CAUTION!

CAUTION! DANGER ZONE ahead. Beware of misinformation on the open internet. Contents of the site are mere opinions and are not always facts!

Tuesday, May 10, 2016

Typedef's must learn to be stronger

A typedef is aliasing a type.

Syntax: typedef type name
Example: typedef int length

Uses:

1. Give meaningful shorter names for really long type names. Specially, in case of template types and function pointers.
typedef myLongLongMeaningfulType tMeaningfulType
typedef std::map<int,std::map<int, std::vector<int> > > doubleIndexMap;

2. Change the underlying type when needed.
Requirement:  I am writing a math library with support for unsigned integers of 8 bit long.

without Typedef,
uint8_t add (uint8_t a, uint8_t b);

Why only 8 bit long!... The same library can handle 16 bit integers.
Uh-Oh! I must change all the types throughout the library.

with Typedef's,
typedef uint8_t supportType_t;
supportType_t add (supportType_t a, supportType_t b);

voila, I can now support 16 bit integers with a single change!!
typedef uint16_t supportType_t;

3. Document Types.
typedef uint8_t length_t; // always stores lengths in uint8 format.
typedef uint8_t area_t; // always stores area's in uint8 format.

The typedef's are weakly typed and cause problems. During syntax and semantic analysis (C++ is not context free grammar), all the alias types are resolved to the same underlying type.

typedef uint8_t length_t;
typedef uint8_t area_t;
length_t
and
area_t
are still uint8.

1. No type safety: The synonym types can be used interchangeably or together,
length_t m_boxLength = 10_CM;
area_t m_boxArea = 100_SQCM;

length_t getLength()
{
     return m_boxArea; // Bug, no compiler warning. both area and length are uint8
}

if(box1.getLength() == box2.getArea()) // Bug, no compiler warning. both area and length are uint8

2. Prevent overloading: Both aliases are actually the same types.

Boost library provides a wrapper to achieve strong type'ing with typedef's with a macro BOOST_STRONG_TYPEDEF.

Epilogue:
There are reasons why no proposal's for strong typedef (N1706 and N1891) made it to the standard. Could be simply because it can be achieved with a wrapper. Not delving deeper into this!