Home > front end >  Customizable way to instantiate objects in 1 expression in C
Customizable way to instantiate objects in 1 expression in C

Time:11-26

In Rust, there is this crate which utilize Rust procedural macro to automatically implement builder pattern for any arbitrary struct defined. As there is no flexible way to instantiate Rust struct with some default and some provided values, this helps a lot in reducing boilerplate.

Is there any similar thing to generate builders automatically in C , as instantiating objects in C also requires a lot of boilerplate (a lot of overloaded constructors to cover all posible combinations of fields or multiple steps initialization), possibly using C/C macros?

As the comments suggested, I added an example to clarify my idea. I want to instantiate class A below by just provide some field I want and leave others as default. If so, I either have to implement a lot of constructors or do multiple steps, instantiate and then override fields I want:

  • Multiple constructors
#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
};
  • Multiple steps
A a;
a.b = "hello";
a.c = 10;

Multiple steps instantiation is actually nice. However, it does not work if I want to have customized instantiation in 1 expression. With builder pattern, I do that in 1 expression by chaining methods like this:

BuilderOfA()
  .a(7)
  .c(8)
  .build();

Can the definition of this builder be automatically generated at compile time in C ? If not, is there anyway I can instantiate an object in a customizable way (by just provide some field I want and leave others as default) without using multiple expressions?

CodePudding user response:

In c 20 you can do this:

struct S {
    std::string str = "Hello";
    float y = 1.0f;
    int x = 10;
};

auto a = S{ .str = "Hi", .x = 8 };
  • Related