I've got a global function that copies relevant bits of one object (or type Source) to another (of type Target), like so:
template<typename Source , typename Target>
void partialCopy( Source& source , Target& target )
{
// perform copy
}
The problem I find with global functions is that, unlike member functions, it is not instantly clear when coding which of the two arguments is the source and which is the target. Therefore I would like to have a member function partialCopy() in every class like so:
struct Foo
{
template<typename T>
void partialCopy( T& target )
{
::partialCopy( *this , target );
}
};
The problem now is that the member function has to be copied to dozens of classes. Is this a tolerable case of copy and paste programming? I've considered putting partialCopy in a header file partialCopy.h and using the preprocessor include to 'inject' it into each class, like so:
struct Foo
{
#include "partialCopy.h"
};
Foo f;
Bar b;
f.partialCopy( b );
Although this works I've never seen it done anywhere and don't know if its unacceptable.
I've already tried putting the partialCopy member function in a common base class and inheriting it but this doesn't work because the this keyword would then refer to the base class and not the derived class.
Is there an even better alternative? Please advise.
Edit
John's suggestion(in a thread that's been deleted) that I perform a static_cast to the derived class in a CRTP base class works nicely. @John please post this an answer and I will mark it as such.
I am posting this as an answer, because in my opinion it's appropriate. Henrik commented first, though. (However, this was also my first thought :))
Use const& (const-reference) for source parameter. That way it's easily distinguishable from the target.
The added benefit is that it will verify and ensure const-correctness of your partial-copy function.
You might also think about overloading it for Source&&. If there are some buffers that are copied directly, your function might take use of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With