使用元编程进行结构初始化/构造 [英] struct initialization/constructor using meta-programming

查看:52
本文介绍了使用元编程进行结构初始化/构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要实现块浮点,我在代码中使用了以下结构:

To implement Block floating point, I'm using the following structure in my code:

struct ff32{
    int16_t _exp;
    int32_t _frac;

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

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

I can instantiate variables of this structure type and initialized them as follow:

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

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

I'd like to extend the constructor to include float data type as follow:

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.

I've already implemented the body of the constructor ff32(float x) but I don't want this code to be executed at run-time for constant float arguments, e.g. ff32(2.7f). Is it possible to achieve this using some kind of meta-programming? I should also mention that my tool-chain only supports C++11.

推荐答案

此处不需要元编程.

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

The function ff32(float x) will be created in any case, but as Klaus mentioned, you can rely on compiler optimization to replace it's result on constexpr floats with the respective values without calling the function in run-time. Simply use the following calculations (that can be performed in compilation-time):

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)
    {}
};

您可以在此处观看代码的汇编.确保使用-O3标志,并查看它在constexpr浮点数上如何工作.

you can watch the assembly your code compiles to here. Make sure to use the -O3 flag and see how this works on constexpr floats.

这篇关于使用元编程进行结构初始化/构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆