how to assign multiple values into a struct at once?

前端 未结 6 1927
执笔经年
执笔经年 2020-12-02 13:15

I can do this on initialization for a struct Foo:

Foo foo =  {bunch, of, things, initialized};

but, I can\'t do this:

Foo f         


        
6条回答
  •  温柔的废话
    2020-12-02 13:40

    In C++11 you can perform multiple assignment with "tie" (declared in the tuple header)

    struct foo {
        int a, b, c;
    } f;
    
    std::tie(f.a, f.b, f.c) = std::make_tuple(1, 2, 3);
    

    If your right hand expression is of fixed size and you only need to get some of the elements, you can use the ignore placeholder with tie

    std::tie(std::ignore, f.b, std::ignore) = some_tuple; // only f.b modified
    

    If you find the syntax std::tie(f.a, f.b, f.c) too code cluttering you could have a member function returning that tuple of references

    struct foo {
        int a, b, c;
        auto members() -> decltype(std::tie(a, b, c)) {
            return std::tie(a, b, c);
        }
    } f;
    
    f.members() = std::make_tuple(1, 2, 3);
    

    All this ofcourse assuming that overloading the assignment operator is not an option because your struct is not constructible by such sequence of values, in which case you could say

    f = foo(1, 2, 3);
    

提交回复
热议问题