Convenient C++ struct initialisation

后端 未结 13 737
谎友^
谎友^ 2020-12-07 10:15

I\'m trying to find a convenient way to initialise \'pod\' C++ structs. Now, consider the following struct:

struct FooBar {
  int foo;
  float bar;
};
// jus         


        
13条回答
  •  一向
    一向 (楼主)
    2020-12-07 10:52

    Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC.

    #include 
    #include 
    
    struct hello_world {
        const char* hello;
        const char* world;
    };
    
    int main () 
    {
        hello_world hw = {
            .hello = "hello, ",
            .world = "world!"
        };
    
        std::cout << hw.hello << hw.world << std::endl;
        return 0;
    }
    

    GCC Demo MSVC Demo

提交回复
热议问题