Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
Artur Pyszczuk Avatar asked May 08 '18 08:05

Artur Pyszczuk


People also ask

What is aggregate initialization in C ++?

Explanation. Aggregate initialization is a form of list-initialization, which initializes aggregates. An aggregate is an object of the type that is one of the following. array type. class type (typically, struct or union), that has.

What is member initialization list in c++?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

What is brace initialization?

If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization: C++ Copy.

How to initialize a class member in c++?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.


1 Answers

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.

like image 74
wooooooooosh Avatar answered Oct 20 '22 12:10

wooooooooosh