I am working on a piece of code that copies a ‘Person’ object from one data representation to another. The names in each class (name, address, title) match, and all types are strings. For each field I want to apply the same transformation, based on some condition that also depends on the field name. The tricky part is that the repeating code uses function suffixes that are based on the field name. It looks something like this:
LibraryA::Person person1;
LibraryB::Person person2;
if (person1.name_valid() && [...somestuff...]) {
string *v = SomeOtherFunction(person.name())
person2.set_name(v);
}
if (person1.address_valid() && [...somestuff...]) {
string *v = SomeOtherFunction(person.address())
person2.set_address(v);
}
if (person1.title_valid() && [...somestuff...]) {
string *v = SomeOtherFunction(person.title())
person2.set_title(v);
}
Is there a trick (or technique 🙂 ) to factor out the repetitive part to a template? I’d prefer a solution that does not involve defining a macro (that would be too easy 🙂 )
This fits your requirements, but whether I would use it or not is a different question. Only if there is a huge amount of repetition I would go through this path, and then I would combine it with a macro to simplify the calling code:
Used as:
And combined with a local macro: