CPPPROGLIB Telegram 6102
⚡️ Designated Initializers — именованная инициализация из C++20

Если устали помнить порядок полей в структурах и случайно их путать, то 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++ разработчика

#буст
Please open Telegram to view this post
VIEW IN TELEGRAM
👍104



tgoop.com/cppproglib/6102
Create:
Last Update:

⚡️ Designated Initializers — именованная инициализация из C++20

Если устали помнить порядок полей в структурах и случайно их путать, то 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++ разработчика

#буст

BY Библиотека C/C++ разработчика | cpp, boost, qt


Share with your friend now:
tgoop.com/cppproglib/6102

View MORE
Open in Telegram


Telegram News

Date: |

How to Create a Private or Public Channel on Telegram? Each account can create up to 10 public channels "Doxxing content is forbidden on Telegram and our moderators routinely remove such content from around the world," said a spokesman for the messaging app, Remi Vaughn. So far, more than a dozen different members have contributed to the group, posting voice notes of themselves screaming, yelling, groaning, and wailing in various pitches and rhythms. Matt Hussey, editorial director of NEAR Protocol (and former editor-in-chief of Decrypt) responded to the news of the Telegram group with “#meIRL.”
from us


Telegram Библиотека C/C++ разработчика | cpp, boost, qt
FROM American