1

As before I try to "emule" float template parameters based on its IEEE754 wrinting thanks to reinterpret_cast. I am using MSVC 2005 compiler (it doesn't support c++11).

Here is the code :

#include <iostream>

#ifdef _MSC_VER
    typedef unsigned __int32 uint32_t;
#else
#    include <stdint.h>
#endif

template <uint32_t T>
union Other
{
    static const uint32_t i = T;
    static const float x;
};

template <uint32_t T>
const float Other<T>::x = reinterpret_cast<const float&>(Other<T>::i);

union Test
{
    static const float x;
    static const uint32_t i;
};

const float Test::x = 3.141592f;

const uint32_t Test::i = reinterpret_cast<const uint32_t&>(Test::x);

int main() 
{
    std::cout << Other<0x40490fdb>::x << std::endl; //works
    std::cout << Other<Test::i>::x << std::endl; //doesn't compile
    return 0;
}

As you can see I can't get ieee754 writing of a float at compile time. Does it compiles with another compiler ? If not why ? Is it possible to achieve this conversion at compile time without c++11 ?

Community
  • 1
  • 1
matovitch
  • 1,264
  • 11
  • 26
  • It looks like you're trying to emulate a [`union`](http://en.cppreference.com/w/cpp/language/union) at compile time? Can you please explain why you want that (especially the compile-time requirement)? (You might want to read [about the XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).) – Some programmer dude Apr 08 '14 at 09:20
  • Indeed a union may be a better choice but it doesn't solve my problem. In fact, I was looking for a more practical way to pass floating points template parameters than `MyStruct<314159265359, 100000000000>`...now it's just for fun. ;-) – matovitch Apr 08 '14 at 09:38
  • Nobody codes in C++ just for fun. Unless you are a masochist. – Shoe Apr 08 '14 at 15:12
  • @Jefffrey As masochist as using MSVC 2005...I knew my employer was sadistic ! ;-) – matovitch Apr 08 '14 at 15:22

0 Answers0