tgoop.com/cppproglib/6102
Create:
Last Update:
Last Update:
Если устали помнить порядок полей в структурах и случайно их путать, то designated initializers
могут решить эту проблему.Designated initializers
позволяют инициализировать структуры по именам полей, делая код более читаемым и безопасным.
struct Point {
int x, y, z;
};
Point p{.x = 10, .y = 20, .z = 30};
struct Config {
std::string host = "localhost";
int port = 8080;
bool ssl_enabled = false;
int timeout_ms = 5000;
};
// Указываем только нужные поля
Config cfg{
.host = "example.com",
.ssl_enabled = true
}; // port и timeout_ms получат значения по умолчанию
struct Database {
std::string connection_string;
int max_connections = 10;
};
struct AppConfig {
Database db;
std::string log_level = "INFO";
};
AppConfig config{
.db = {.connection_string = "postgresql://...", .max_connections = 20},
.log_level = "DEBUG"
};
struct DrawOptions {
bool fill = false;
int line_width = 1;
std::string color = "black";
float opacity = 1.0f;
};
void draw_rectangle(int x, int y, int w, int h, DrawOptions opts = {}) {
// implementation
}
// Явно указываем только нужные опции
draw_rectangle(10, 20, 100, 50, {
.fill = true,
.color = "red",
.opacity = 0.8f
});
Библиотека C/C++ разработчика
#буст