方便的C ++结构初始化

问题描述

| 我正在尝试寻找一种方便的方法来初始化\'pod \'C ++结构。现在,考虑以下结构:
struct FooBar {
  int foo;
  float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
如果我想方便地用C(!)初始化它,我可以简单地写:
/* A */ FooBar fb = { .foo = 12,.bar = 3.4 }; // illegal C++,legal C
请注意,我想明确地避免使用以下表示法,因为如果将来我在结构中进行任何更改,它都会令我不寒而栗:
/* B */ FooBar fb = { 12,3.4 }; // legal C++,legal C,bad style?
为了在C ++中实现与
/* A */
示例相同(或至少相似)的功能,我将必须实现一个白痴的构造函数
FooBar::FooBar(int foo,float bar) : foo(foo),bar(bar) {}
// ->
/* C */ FooBar fb(12,3.4);
哪个对开水有益,但不适合懒人(懒惰是一件好事,对吗?)。同样,它与ѭ5例子一样糟糕,因为它没有明确说明哪个值分配给哪个成员。 所以,我的问题基本上是我如何在C ++中实现类似于
/* A */
或更好的东西? 另外,我可以向我解释一下为什么我不想这样做(即为什么我的思维模式不好)。 编辑 方便起见,我的意思是也可维护且非冗余。     

解决方法

        指定的初始化将在c ++ 2a中受支持,但您不必等待,因为GCC,Clang和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示范     ,        由于C ++中不允许使用
style A
,并且您不希望
style B
,那么使用
style BX
怎么样:
FooBar fb = { /*.foo=*/ 12,/*.bar=*/ 3.4 };  // :)
至少在某种程度上有所帮助。     ,        您可以使用lambda:
const FooBar fb = [&] {
    FooBar fb;
    fb.foo = 12;
    fb.bar = 3.4;
    return fb;
}();
可以在Herb Sutter的博客上找到有关此习语的更多信息。     ,        您的问题有些困难,因为即使函数:
static FooBar MakeFooBar(int foo,float bar);
可以称为:
FooBar fb = MakeFooBar(3.4,5);
由于内置数字类型的升级和转换规则。 (C从未真正过强类型化) 在C ++中,尽管借助模板和静态断言,您仍可以实现所需的结果:
template <typename Integer,typename Real>
FooBar MakeFooBar(Integer foo,Real bar) {
  static_assert(std::is_same<Integer,int>::value,\"foo should be of type int\");
  static_assert(std::is_same<Real,float>::value,\"bar should be of type float\");
  return { foo,bar };
}
在C语言中,您可以命名参数,但是您将永远无法更进一步。 另一方面,如果您想要的只是命名参数,那么您将编写许多繁琐的代码:
struct FooBarMaker {
  FooBarMaker(int f): _f(f) {}
  FooBar Bar(float b) const { return FooBar(_f,b); }
  int _f;
};

static FooBarMaker Foo(int f) { return FooBarMaker(f); }

// Usage
FooBar fb = Foo(5).Bar(3.4);
而且,如果您愿意,您可以加入类型促进保护功能。     ,        将竞争对象提取到描述它们的函数中(基本重构):
FooBar fb = { foo(),bar() };
我知道样式与您不希望使用的样式非常接近,但是它可以更轻松地替换常量值,并且可以对常量值进行解释(因此无需编辑注释)(如果更改了)。 您可以做的另一件事(因为您很懒惰)是使构造函数内联,因此您不必键入太多内容(删除\“ Foobar :: \”以及在h和cpp文件之间切换所花费的时间):
struct FooBar {
  FooBar(int f,float b) : foo(f),bar(b) {}
  int foo;
  float bar;
};
    ,        许多编译器的C ++前端(包括GCC和clang)都了解C初始化程序语法。如果可以,只需使用该方法。     ,        C ++的另一种方式是
struct Point
{
private:

 int x;
 int y;

public:
    Point& setX(int xIn) { x = Xin; return *this;}
    Point& setY(int yIn) { y = Yin; return *this;}

}

Point pt;
pt.setX(20).setY(20);
    ,        选项D:
FooBar FooBarMake(int foo,float bar)
合法C,合法C ++。轻松优化POD。当然,没有命名参数,但这就像所有C ++一样。如果要使用命名参数,则目标C应该是更好的选择。 选项E:
FooBar fb;
memset(&fb,sizeof(FooBar));
fb.foo = 4;
fb.bar = 15.5f;
合法C,合法C ++。命名参数。     ,        我知道这个问题很古老,但是有一种解决方法,直到C ++ 20最终将此功能从C引入C ++为止。解决此问题的方法是,将预处理器宏与static_asserts结合使用以检查初始化是否有效。 (我知道宏通常是不好的,但是在这里我看不到其他方法。)请参见下面的示例代码:
#define INVALID_STRUCT_ERROR \"Instantiation of struct failed: Type,order or number of attributes is wrong.\"

#define CREATE_STRUCT_1(type,identifier,m_1,p_1) \\
{ p_1 };\\
static_assert(offsetof(type,m_1) == 0,INVALID_STRUCT_ERROR);\\

#define CREATE_STRUCT_2(type,p_1,m_2,p_2) \\
{ p_1,p_2 };\\
static_assert(offsetof(type,INVALID_STRUCT_ERROR);\\
static_assert(offsetof(type,m_2) >= sizeof(identifier.m_1),INVALID_STRUCT_ERROR);\\

#define CREATE_STRUCT_3(type,p_2,m_3,p_3) \\
{ p_1,p_3 };\\
static_assert(offsetof(type,m_3) >= (offsetof(type,m_2) + sizeof(identifier.m_2)),INVALID_STRUCT_ERROR);\\

#define CREATE_STRUCT_4(type,p_3,m_4,p_4) \\
{ p_1,p_4 };\\
static_assert(offsetof(type,m_4) >= (offsetof(type,m_3) + sizeof(identifier.m_3)),INVALID_STRUCT_ERROR);\\

// Create more macros for structs with more attributes...
然后,当您具有带有const属性的结构时,可以执行以下操作:
struct MyStruct
{
    const int attr1;
    const float attr2;
    const double attr3;
};

const MyStruct test = CREATE_STRUCT_3(MyStruct,test,attr1,1,attr2,2.f,attr3,3.);
这有点不方便,因为您需要为每个可能数量的属性使用宏,并且需要在宏调用中重复实例的类型和名称。同样,您不能在return语句中使用宏,因为断言是在初始化之后进行的。 但这确实解决了您的问题:更改结构时,调用将在编译时失败。 如果您使用C ++ 17,甚至可以通过强制使用相同的类型来使这些宏更加严格,例如:
#define CREATE_STRUCT_3(type,INVALID_STRUCT_ERROR);\\
static_assert(typeid(p_1) == typeid(identifier.m_1),INVALID_STRUCT_ERROR);\\
static_assert(typeid(p_2) == typeid(identifier.m_2),INVALID_STRUCT_ERROR);\\
static_assert(typeid(p_3) == typeid(identifier.m_3),INVALID_STRUCT_ERROR);\\
    ,        在C ++中ѭ5的方式还不错,C ++ 0x还将扩展语法,因此对C ++容器也很有用。我不明白你为什么称它为不良风格? 如果要使用名称来指示参数,则可以使用boost参数库,但是它可能会使不熟悉它的人感到困惑。 对结构成员进行重新排序就像对函数参数进行重新排序一样,如果您不十分仔细地进行重构,则可能会导致问题。     ,这个语法呢?
typedef struct
{
    int a;
    short b;
}
ABCD;

ABCD abc = { abc.a = 5,abc.b = 7 };
刚刚在Microsoft Visual C ++ 2015和g ++ 6.0.2上进行了测试。工作正常。 如果要避免重复变量名称,也可以创建特定的宏。     ,        对我来说,允许内联inizialization的最懒惰的方法是使用此宏。
#define METHOD_MEMBER(TYPE,NAME,CLASS) \\
CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \\
TYPE NAME;

struct foo {
    METHOD_MEMBER(string,foo)
    METHOD_MEMBER(int,foo)
    METHOD_MEMBER(double,foo)
};

// inline usage
foo test = foo().set_attr1(\"hi\").set_attr2(22).set_attr3(3.14);
该宏创建属性和自引用方法。