Avoiding a template creating new immutable instances in C ++

I work with persistent data structures.
I will have the complex class that I need to create a new instance, but with one or more fields with different values.

struct Data {
  int field1; int field2; int field3; // etc.
public:
  Data withField2(int newField2) {
      return { field1, newField2, field3 };
  }
};

int main()
{
  Data d = { 1, 2, 3 };
  std::cout << d.field2 << std::endl;
  Data newD = d.withField2(4);
  std::cout << newD.field2 << std::endl;
}

In the worst case scenario, I can create a bunch of methods withField1(newField1Value)as described above, but there will be enough fields to make them very dirty.
In addition, I may need new values ​​for several fields, so there may be many more.

So is there any magic way to say

Data newData = data.with(field1Name = newField1, field2Name = newField2)

or something similar?

+4
source share
2 answers

, - :

#include<iostream>
#include<functional>

struct Data {
  int field1; int field2; int field3; // etc.

  template<int Data::*M>
  Data withField(int value) {
    Data cpy = *this;
    cpy.*M = value;
    return cpy;
  }
};

int main()
{
  Data d = { 1, 2, 3 };
  std::cout << d.field2 << std::endl;
  Data newD = d.withField<&Data::field2>(4);
  std::cout << newD.field2 << std::endl;
}

, , , withField.

, , , .

, , int.
- :

template<typename T, T Data::*M>
Data withField(T value) {
  Data cpy = *this;
  cpy.*M = value;
  return cpy;
}

:

Data newD = d.withField<int, &Data::field2>(4);
+3

, std::tuple. std::get<N>.

, . , .

+1

Source: https://habr.com/ru/post/1652706/


All Articles