Use of Union with reference

前端 未结 2 1649
野趣味
野趣味 2021-01-05 04:12

At work I\'ve been using linux and the GCC compiler for C++11 and C++14. In some of the code at work, I\'ve used a union to store both a reference and a pointer, as so: (Sim

2条回答
  •  长发绾君心
    2021-01-05 05:11

    In addition to @Brian: You can make it compile by using e.g. std::reference_wrapper instead of a plain reference:

    #include 
    
    struct MyStruct
    {
        //Stuff
        union { std::reference_wrapper x; double* x_ptr; };
        MyStruct(double& value) : x(value) {}
        //More stuff
    };
    
    int main()
    {
        double value = 123;
        MyStruct myStruct(value);
    }
    

    live example

提交回复
热议问题