A “hack” to get float template parameter working compiles but segfaulted on both g++ and clang

心不动则不痛 提交于 2019-12-05 16:35:46

Your code reinterprets 0x40490fdb as a pointer to float, not as the hex value of a float. Hence the segfault.

Try the following:

constexpr float uint32_to_float(uint32_t val) {
  return *reinterpret_cast<float*>(&val);
}

template <uint32_t T>
const float MyStruct<T>::value = uint32_to_float(T);

The segfault in the question was a vulgar mistake but the question remains. How to pass a float in ieee754 format as a template argument ?

The C++11 way

This solution was given by NPE (modified but not tested) :

#include <iostream>
#include <cstdint>

template <uint32_t T>
struct MyStruct
{
    static const float value;
}; 

constexpr float uint32_to_float(uint32_t val) {
    return reinterpret_cast<float&>(val);
}

template <uint32_t T>
const float MyStruct<T>::value = uint32_to_float(T);

int main()
{
    const uint32_t pi = 0x40490fdb;
    std::cout << MyStruct<pi>::value << std::endl;
}

The old fashioned way

Relativly small, I'm proud of it ! :-)

#include <iostream>
#include <stdio.h>

template <uint32_t T>
union MyStruct
{
    static const uint32_t int_val = T;
    static const float    flt_val;
};

template <uint32_t T>
const float MyStruct<T>::flt_val = reinterpret_cast<const float&>(MyStruct<T>::int_val);

int main()
{
    const uint32_t pi = 0x40490fdb;
    std::cout << MyStruct<pi>::flt_val << std::endl;
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!