
Martin Bonner wrote:
Johan RĂ¥de wrote:
I still find it hard to believe that the volatile are needed ;-)
It is not.
If volatile is not present, then you can't instantiate the template with T="volatile float" for example. (Similarly you need the "const" so that you can invoke with T="const float".)
template<class T, class S> T binary_cast( S const & s ) { T t; memcpy( &t, &s, sizeof(T) ); return t; } You need the const on s to be able to pass rvalues such as 1.0, not for const lvalues. It is true that binary_cast will fail to compile if you pass a volatile object as source, this is intentional; accessing a volatile object as a sequence of bytes can be dangerous if that volatile object is an I/O port. You definitely don't need a volatile on t, it only inhibits useful optimizations.