WEBINAR:

On-Demand

Equivalent functions for Unchecked Conversion

Question:

Are there any functions/libraries that can perform the Unchecked_Conversion function in Ada? We are writing a program that will read a bitstream. Upon determining the type, we want to able to sort of "cast" this bitstream to the correct object in C++.

Answer:

Sure there is a way to do that. However, perhaps I should explain what Unchecked_Conversion in Ada does, for C++ programmers who aren't fluent speakers of Ada.

Ada is a strongly-typed language. Therefore, it is does not allow the programmer to assign variables of different types to one another. For example, assigning a variable of type Float to a variable of type Integer requires an explicit cast. In C++, on the other hand, the cast isn't required in this case; it's performed implicitly.

Of course, real world programming requires some bit fiddling tricks and brute force casts, especially when dealing with low level functions that de-serialize objects from a stream of bits. For this purpose, Ada has the generic procedure Unchecked_Conversion, which takes as an argument one type, and returns another. The only constraint on this is that they must be the same size.

There are two ways to achieve this in C++. The first consists of using memcpy. However, this is kludgy and requires a function call with its associated overhead.

The second way relies on the built-in operator reinterpret_cast. As the name suggests, this operator casts one type to another by interpreting the bit pattern of the argument.

In general, you can convert non-related types by using reinterpret_cast to coerce the source's pointer to the target's pointer, and then dereference the resultant pointer. Thus, to convert a stream of bytes into a Person object, you would do the following:

reinterpret_cast takes the argument stream (which is a pointer to char), coerces it to a pointer to Person, the target type (specified in the angle brackets) and then, the resultant pointer is dereferenced (the asterisk before reinterpret_cast). The operation yields a temporary object of type Person that is assigned to a Person object per. Unlike Ada, C++ does not require that the source and the target types have the same size; rather, C++ is true to the "trust the programmer" idiom.