c++c++17multiple-return-values

Initialization of multiple members using multiple return value


Since C++17 I can do

std::pair<int, double> init () {
    return std::make_pair (1, 1.2);
}

void foo () {
    const auto [x, y] = init ();
    std::cout << x << " " << y << "\n";
}

That is cool, but is there any way I can initialize multiple members at once? I mean:

struct X {
    X () : [x, y] {read_from_file_all_values ()} {}

    std::pair<int, double> read_from_file_all_values () {
        // open file, read all values, return all
        return std::make_pair (1, 1.2);
    }

    const int x;
    const double y;
};

I know, this does not work because of the syntax. I also know that I could store all the values in the appropriate std::pair member inside X and make getters which overload the ugly std::get<N> () syntax, but is there any way I can initialize multiple members with single init() function? Since those members are const I can not do this in constructor's body.


Solution

  • Not using structured binding, but you could have a private constructor taking in a std::pair and init the consts. Then have your default constructor delegate to this constructor with the result of your function.