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
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