方便的 C++ 结构初始化

2021-12-23 00:00:00 initialization struct c++

我正在尝试找到一种方便的方法来初始化pod"C++ 结构.现在,考虑以下结构:

I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:

struct FooBar {
  int foo;
  float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;

如果我想在 C (!) 中方便地初始化它,我可以简单地写:

If I want to conveniently initialise this in C (!), I could simply write:

/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C

请注意,我想明确避免使用以下符号,因为如果我将来更改结构中的任何内容,我觉得它会折断我的脖子:

Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:

/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?

要在 C++ 中实现与 /* A */ 示例中相同(或至少相似)的效果,我必须实现一个烦人的构造函数:

To achieve the same (or at least similar) in C++ as in the /* A */ example, I would have to implement an annoying constructor:

FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);

感觉多余和不必要的.此外,它几乎与 /* B */ 示例一样糟糕,因为它没有明确说明哪个值属于哪个成员.

Which feels redundant and unnecessary. Also, it is pretty much as bad as the /* B */ example, as it does not explicitly state which value goes to which member.

所以,我的问题基本上是如何在 C++ 中实现类似于 /* A */ 或更好的东西?或者,我可以解释为什么我不应该这样做(即为什么我的心理范式很糟糕).

So, my question is basically how I can achieve something similar to /* A */ or better in C++? Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).

编辑

通过方便,我的意思是也可维护和非冗余.

By convenient, I mean also maintainable and non-redundant.

推荐答案

C++2a 将支持指定的初始化,但您不必等待,因为它们是 官方支持 GCC、Clang 和 MSVC.

Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC.

#include <iostream>
#include <filesystem>

struct hello_world {
    const char* hello;
    const char* world;
};

int main () 
{
    hello_world hw = {
        .hello = "hello, ",
        .world = "world!"
    };
    
    std::cout << hw.hello << hw.world << std::endl;
    return 0;
}

GCC 演示MSVC 演示

正如 @Code Doggo 所指出的,任何使用 Visual Studio 2019 的人都需要为C++ 语言标准"设置 /std:c++latestConfiguration Properties -> 下包含的字段C/C++ ->语言.

As @Code Doggo noted, anyone who is using Visual Studio 2019 will need to set /std:c++latest? for the "C++ Language Standard" field contained under Configuration Properties -> C/C++ -> Language.

相关文章