方便的C ++结构初始化

如何解决方便的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);
该宏创建属性和自引用方法。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-