简体   繁体   English

C++20:强制使用指定的初始化器来模拟命名的 function arguments

[英]C++20: Force usage of designated initializers to emulate named function arguments

I am a big fan of using ad-hoc structs and designated initializers to emulate named parameters for my functions.我非常喜欢使用临时结构和指定的初始化程序来模拟我的函数的命名参数。

struct Args {
    int a;
    int b;
};

int f(Args a) {
    return a.a + a.b;
}

int g() {
    return f({.a = 1, .b = 2}); // Works! That's what I want.
    return f({1, 2}); // Also works. I want to forbid this, though.
}

However, those structs can still be initialized by a positional initializer list.但是,这些结构仍然可以通过位置初始化列表进行初始化。 Ie, you can still call f({1, 2}) .即,您仍然可以调用f({1, 2})

I want to forbid this and force the caller to explicitly name the parameters also at the call-site.我想禁止这样做并强制调用者在调用点也显式地命名参数。 How can I do so in C++20?我如何在 C++20 中这样做?

The best way is just code review.最好的方法就是代码审查。 Tell people to use designated initializers.告诉人们使用指定的初始化器。 Designated initializers are awesome, people like using them.指定的初始化器很棒,人们喜欢使用它们。 This is really more of a social problem than a technical one.这实际上是一个社会问题,而不是技术问题。

If you really want to give a nudge, you could always stick in some truly awful data members first, like so:如果你真的想轻推一下,你总是可以先加入一些真正糟糕的数据成员,就像这样:

class Args {
    struct Key { explicit Key() = default; };
    struct StopIt { StopIt(Key) { } };

public:
    StopIt asdfjkhasdkljfhasdf = Key();

    int a;
    int b;
};

Args is still an aggregate, we just have this extra leading data member spelled with whatever came out when I just banged on my keyboard. Args仍然是一个集合,我们只是将这个额外的前导数据成员拼写为我刚刚敲击键盘时出现的任何内容。 It has a default member initializer - however that initializer is private to Args and only Args knows how to construct it.它有一个默认的成员初始化器 - 但是该初始化器是Args私有的,只有Args知道如何构造它。

So the user cannot correctly provide an initializer for that particular member, they have to rely on the default member initializer to initialize it correctly.所以用户不能正确地为该特定成员提供初始化程序,他们必须依靠默认成员初始化程序来正确初始化它。 And since it goes first, they have to rely on designated initialization in order to be able to initialize any of the other members.并且由于它先行,它们必须依赖指定的初始化才能初始化任何其他成员。

But also... this is kind of a silly thing to write?而且……这样写有点傻? Just tell people to use designated initialization.只是告诉人们使用指定的初始化。


Technically, they could write f({Args().asdfjkhasdkljfhasdf, 1, 2}) in this case, but this seems like we're going for absurdity or spite at this point. 从技术上讲,他们可以在这种情况下写f({Args().asdfjkhasdkljfhasdf, 1, 2}) ,但这似乎是我们在这一点上的荒谬或恶意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM