C++ Equivalent to Designated Initializers?

后端 未结 6 1868
萌比男神i
萌比男神i 2020-11-29 05:31

Recently I\'ve been working on some embedded devices, where we have some structs and unions that need to be initialized at compile time so that we can keep certain things in

6条回答
  •  醉酒成梦
    2020-11-29 06:36

    Building on Shing Yip's answer, and with benefit of 3 year's time, C++11 can now guarantee compile time initialization:

    union Bar
    {
        constexpr Bar(int a) : a_(a) {}
        constexpr Bar(float b) : b_(b) {}
        int a_;
        float b_;
    };
    
    extern constexpr Bar bar1(1);
    extern constexpr Bar bar2(1.234f);
    

    Assembly:

        .globl  _bar1                   ## @bar1
        .p2align    2
    _bar1:
        .long   1                       ## 0x1
    
        .globl  _bar2                   ## @bar2
        .p2align    2
    _bar2:
        .long   1067316150              ## float 1.23399997
    

提交回复
热议问题