c++ - 具有不同参数顺序的聚合初始化

标签 c++ c++17

有没有什么方法可以按照与声明顺序不同的顺序指定参数?

例如,假设我有以下结构:

struct Coord
    {
        int x, y;
    };

我可以将它初始化为

auto a = Coord{ y(5),x(4) };

请注意,我问这个问题是出于好奇,我真的不需要做这样的事情。但是我想知道我是否可以在不声明构造函数但指定参数的情况下初始化结构。

最佳答案

很遗憾,您无法更改结构成员构造的顺序。使用 C++20,您可以按名称指定成员(参见 designated initializers )。不幸的是,初始化的名称必须与成员的顺序相同。

这是来自 cppreference(上面的链接)的引述:

Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.

struct Coord
{
    int x, y;
};

初始化:

auto a = Coord{ .x=4, .y = 5}; // Ok with C++20

但这行不通(见上面的引述):

auto a = Coord{ .y=5, .x = 4}; // ERROR

对于不同的顺序,您必须定义构造函数或辅助函数。

试试看 compiler explorer .

关于c++ - 具有不同参数顺序的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323127/

相关文章:

c++ - 清除单向链表

c++ - 使用 Cmake,如何防止库源包含在我的 IDE 中?

c++ - 将 QVariant 分配给 QVariant 时应用程序崩溃

c++ - <=> 在 c++20 之前的代码中的合法出现

c++ - 每当使用 constexpr 指定调用的函数时,将委托(delegate)方法声明为 constexpr

c++ - clang std::isspace 编译错误

c++ - 只有负数正确加法

c++ - std 中是否有折叠算法(或失败 : boost) available?

c++ - 一个可能失败的函数应该返回什么?

c++ - 有什么方法可以在不复制的情况下从 std::ostringstream 获取 std::string_view ?