C ++ strict anti-agnostic casting

I read a lot of QAs about a strict alias here on Stack Overflow, but they are all pretty common, and the discussion always tends to refer to the deep details of the C ++ standard, which are almost always hard to get right. Especially when the standard does not speak directly, but describes something in a dirty obscure way. So my question is probably a possible duplication of QA tones here, but please just answer a specific question:

Is this the right way to do "nonalias_cast" ?:

template<class OUT, class IN>
inline auto nonalias_cast(IN *data) {
    char *tmp = reinterpret_cast<char *>(data);
    return reinterpret_cast<OUT>(tmp);
}

float f = 3.14;
unsigned *u = nonalias_cast<unsigned *>(&f);
*u = 0x3f800000;
// now f should be equal 1.0

I think the answer is no . But are there any good workarounds? Also, of course, turn off the strict smoothing flag. Union is also not a convenient option, unless there is a way to place the hacked node inside the body of the function nonalias_cast. memcpyalso not an option - data changes should be synchronized.

Impossible dream or elusive reality?

UPD:

Good, since we have a negative answer to the question "is this possible?". question, I would like to ask you a question that bothers me:

? , , - " ". , , IEEE-754, this. : ? , " @# $".

+4
3

: , float unsigned, , .

, ? unsigned! float* char* , , . , unsigned, memcpy float* unsigned ( memcpy , ). , .

, , float* unsigned*. , : . , float unsigned*, , , , , - .

+5

"nonalias_cast"?

.

- ?

, .

, &f - unsigned int, .

+5

, nonalias_cast .

Type alias rules are not (directly) about conversion pointers. In fact, none of your transformations have undefined behavior. The rules concern access to an object of a certain type using a pointer of another type.

Regardless of how you convert the pointer, the pointed object is still an object float, and accessing it with the pointer unsignedviolates the rules of type aliases.


Impossible dream or elusive reality?

In standard C ++, this is not possible.

+4
source

All Articles