使用元编程进行结构初始化/构造

时间:2018-11-26 19:28:35

标签: c++ c++11 struct constructor metaprogramming

要实现Block floating point,我在代码中使用以下结构:

struct ff32{
    int16_t _exp;
    int32_t _frac;

    ff32(int16_t e, int32_t f)
        : _exp(e), _frac(f)
    {};
};

我可以实例化这种结构类型的变量并将其初始化如下:

ff32 x(2, 0x60000000);
ff32 y = {2, 0x60000000};

我想扩展构造函数以包括float数据类型,如下所示:

struct ff32{
    int16_t _exp;
    int32_t _frac;

    ff32(int16_t e, int32_t f)
        : _exp(e), _frac(f)
    {};

    ff32(float x)
    {
        // some code that extract _exp and _frac 
        // for a given floating-point number x
    };
};

我已经实现了构造函数ff32(float x)的主体,但是我不希望在运行时为常量float参数执行此代码,例如ff32(2.7f)。是否可以使用某种元编程来实现这一目标?我还应该提到我的工具链仅支持C ++ 11。

1 个答案:

答案 0 :(得分:0)

这里不需要元编程。

在任何情况下都将创建函数ff32(float x),但是正如Klaus所述,您可以依靠编译器优化来用相应的值替换constexpr浮点数的结果,而无需在运行时调用该函数。只需使用以下计算(可以在编译时执行)即可:

struct float32{
    unsigned const bits;
    unsigned const exponent;
    unsigned const fraction;
    bool const sign;

    constexpr float32(float input_float):
        bits(*reinterpret_cast<unsigned*>(&input_float)),
        exponent((bits & 0x7f800000) >> 23),
        fraction((bits & 0x007fffff)),
        sign((bits & 0x80000000) > 0)
    {}
};

您可以观看代码被编译为here的程序集。确保使用-O3标志,并查看它在constexpr浮点数上如何工作。