C++Guns – RoboBlog

14.03.2019

C++ Guns: floating point bit round - p0476r2 Bit-casting object representations

Filed under: Allgemein — Tags: — Thomas @ 10:03

C++20

Low-level code often seeks to interpret objects of one type as another: keep the same bits, but obtain an object of a different type. Doing so correctly is error-prone: using reinterpret_cast or union runs afoul of type-aliasing rules yet these are the intuitive solutions developers mistakenly turn to.

Attuned developers use aligned_storage with memcpy, avoiding alignment pitfalls and allowing them to bit-cast non-default-constructible types.

This proposal uses appropriate concepts to prevent misuse. As the sample implementation demonstrates we could as well use static_assert or template SFINAE, but the timing of this library feature will likely coincide with concept’s standardization.

Furthermore, it is currently impossible to implement a constexpr bit-cast function, as memcpy itself isn’t constexpr. Marking the proposed function as constexpr doesn’t require or prevent memcpy from becoming constexpr, but requires compiler support. This leaves implementations free to use their own internal solution (e.g. LLVM has a bitcast opcode).

We should standardize this oft-used idiom, and avoid the pitfalls once and for all.

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0476r2.html
https://github.com/jfbastien/bit_cast/

Solange wir noch kein C++20 haben um Bit Manipulationen an Gleitkommazahlen vorzunehmen, muss memcpy herhalten.

  double value;

  // float -> integer 
  std::uint64_t n;
  std::memcpy(&n, &value, sizeof(value)); // no aliasing violation

  // Bit Manipulation an Variable 'n'
  // ...

  // integer -> float
  std::memcpy(&value, &n, sizeof(n));

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress