Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typesafe typedef in C++

I would like to use something like typedef in my C++ programs to enhance type safety.

As an example, suppose I have two functions

void function1(unsigned idOfType1);
void function2(unsigned idOfType2);

then I can mistakenly pass idOfType2 to function1 and vice versa. I want the compiler to give me an error in this case. I am aware that I could wrap these unsigned in a struct, but then I'd have to give provide a field name and use . to access them, which is slightly inconvenient. Is there a good way around this?

Edit: As far as I know typedef will not work for this purpose as it is just a shorthand for a type and will not be used for type checking.

like image 872
Paul Avatar asked Mar 06 '12 16:03

Paul


People also ask

What is the use of typedef?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

What is the advantage of using typedef?

Typedefs provide a level of abstraction away from the actual types being used, allowing you, the programmer, to focus more on the concept of just what a variable should mean. This makes it easier to write clean code, but it also makes it far easier to modify your code.

What is a strong typedef?

Strong or opaque typedefs are a very powerful feature if you want to prevent errors with the type system – and as I've been advocating for, you want that. Unlike “normal” typedefs, they are a true type definition: they create a new type and allow stuff like overloading on them and/or prevent implicit conversions.

What is type safety in C?

The C programming language is type-safe in limited contexts; for example, a compile-time error is generated when an attempt is made to convert a pointer to one type of structure to a pointer to another type of structure, unless an explicit cast is used.


1 Answers

Use Boost strong typedef:

typedef creates an alias for an existing type. It does not create a new type that can be used for matching either function or template parameters...

Usage of BOOST_STRONG_TYPEDEF addresses this...

BOOST_STRONG_TYPEDEF is a macro which generates a class named "name" wraps and instance of its primitive type and provides appropriate conversion operators in order to make the new type substitutable for the one that it wraps.

like image 135
Steve Jessop Avatar answered Oct 21 '22 21:10

Steve Jessop