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: |

Read now Commenting about the court's concerns about the spread of false information related to the elections, Minister Fachin noted Brazil is "facing circumstances that could put Brazil's democracy at risk." During the meeting, the information technology secretary at the TSE, Julio Valente, put forward a list of requests the court believes will disinformation. But a Telegram statement also said: "Any requests related to political censorship or limiting human rights such as the rights to free speech or assembly are not and will not be considered." How to create a business channel on Telegram? (Tutorial) To view your bio, click the Menu icon and select “View channel info.”
from us


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