Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating yourself for structs with default values

Tags:

c++

struct

#include <iostream>
#include <string>
#include <cassert>

struct Foo
{
  std::string bar = "standard";
  int x = 1;
  int y = 1;

  bool operator==(const Foo&) const = default;
  bool operator!=(const Foo&) const = default;

  void ResetToStandard()
  {
    bar = "standard";
    x = 1;
    y = 1;
  }  
};

int main(int argc, char* argv[])
{
  Foo f, g;
  g.bar = "Hello world!";
  g.x = 123;
  g.y = 234;
  g.ResetToStandard();
  assert(f == g);
}

In this sample code (very simplified real world code) I have a struct Foo whose fields have default values. There is also a ResetToStandard function that sets all field to their standard value, but all the values are repeated in this function.

Then I came up with this, which works fine.

void ResetToStandard()
{
  *this = Foo();
}

Is this pattern common? Is this the idiomatic way?

like image 756
Jabberwocky Avatar asked Oct 15 '25 03:10

Jabberwocky


1 Answers

I would use *this = {} like this (to reassign this from default constructed object).
Which should use the move constructor.

#include <iostream>
#include <string>
#include <cassert>

struct Foo
{
    std::string bar = "standard";
    int x = 1;
    int y = 1;

    bool operator==(const Foo&) const = default;
    bool operator!=(const Foo&) const = default;

    void ResetToStandard()
    {
        *this = {};
    }
};

int main(int argc, char* argv[])
{
    Foo f, g;
    g.bar = "Hello world!";
    g.x = 123;
    g.y = 234;
    g.ResetToStandard();
    assert(f == g);
}
like image 174
Pepijn Kramer Avatar answered Oct 17 '25 22:10

Pepijn Kramer