Is there a way of mimicking Kotlin's data class 'copy()' in C++ ?
This allows copying the object and modify specific parts of it within a single expression, see Kotlin example:
data class SomeData(val a: Int, val b: String)
...
SomeData(a = 10, b = "10").copy(b = "ten")
In C++20 I can do
struct SomeData {
int a;
string b;
};
...
SomeData sd1 = { .a = 10, .b = "10" };
SomeData sd2 = { .a = sd1.a, .b = "ten" };
but this gets very clunky and unsafe when structs get larger and larger.
I am considering writing my own function that would behave as a copy constructor, but would also take an std::initializer_list to apply the designated initialization over the copied object.
- Is there any language support for this I could take advantage or I am left with my own function only ?
note: I am unable to use C++23 - Any suggestions for my own function implementation ?
Immediately invoked lambda
One alternative that connects data member names with the value to be changes are using an immediately invoked lambda:
A macro could potentially be used to make this into a simpler form.
Variadics and pointer-to-members
Another approach that I was hoping would end up less clunky (but didn't) are to use variadic auto non-type template parameters with pointer-to-members as arguments, to specify which members of a modified copy that you would like to replace along with their new values:
This also emphasizes "specify the members you want to change" semantics as opposed to the one you list which have "specify the members you want to keep and change" semantics. This differentiation could help when structs are becoming bigger, in case they are generally more similar than dissimilar (still the concern of separating member reference to the value that should be assigned to it).
You could use a macro to make this less clunky, however with the general concerns of using macros.
Useful third party libs?
boost_pfr could be used to create a briefer (tuple-like referencing)
modifiedCopyAPI that takes data member indices as non-type template parameters instead of pointers-to-members: