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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With