在Rust中,有这样一个板条箱,它使用Rust过程宏为任何定义的任意结构自动实现构建器模式。由于没有灵活的方法使用某些默认值和一些提供的值实例化锈蚀结构,这在减少样板方面有很大帮助。
在C++中是否有类似的东西来自动生成构建器,因为在C++中实例化对象也需要大量的样板(大量重载的构造函数来覆盖所有可定位的字段组合或多步初始化),可能使用C/C++宏?
正如评论所建议的那样,我增加了一个例子来澄清我的想法。我想在下面实例化A类,只需提供一些我想要的字段,并将其他字段保留为默认值。如果是这样的话,我要么必须实现许多构造函数,要么执行多个步骤,实例化,然后重写我想要的字段:
#include <string>
#include <iostream>
class A
{
public:
int a = 2;
std::string b = "b";
int c = 5;
std::string d = "d";
A() {}
A(int a) { this->a = a; }
A(std::string b) { this->b = b; }
A(int a, std::string b)
{
this->a = a;
this->b = b;
}
// ... more constructors to cover all combinations
// this might not even work as some combinations might
// have similar types, which prevent overloading them
};A a;
a.b = "hello";
a.c = 10;多个步骤实例化实际上很好。但是,如果我想要在1表达式中进行自定义实例化,则不起作用。在构建器模式中,我通过如下的链接方法在1表达式中实现了这一点:
BuilderOfA()
.a(7)
.c(8)
.build();能否在C++编译时自动生成此构建器的定义?如果没有,我是否可以在不使用多个表达式的情况下以可定制的方式实例化一个对象(只需提供我想要的一些字段,并将其他字段保留为默认值)?
发布于 2021-11-25 17:22:40
在c++ 20中,您可以这样做:
struct S {
std::string str = "Hello";
float y = 1.0f;
int x = 10;
};
auto a = S{ .str = "Hi", .x = 8 };https://stackoverflow.com/questions/70114257
复制相似问题