I have a C struct
from a third-party library that I do not control, and I'd like to extend it with some non-virtual methods by wrapping it in a C++ class. For example:
struct Base
{
int x;
};
class Wrapper : public Base
{
public:
int square() const { return x * x; }
};
However, there are various existing APIs (which I again do not control) that might return the C struct
by value or that might use it as a member to some other aggregate data type. I therefore cannot force use of my wrapper class everywhere.
Is there a way to wrap the C struct
such that conversions between it and the wrapper class are zero-cost? That is, I don't mind doing something like Wrapper(arrayOfBases[0]).square()
, but I would prefer to avoid unnecessarily copying the Base
object.
Ideally I'd do: static_cast<Wrapper&>(arrayOfBases[0]).square()
, but my understanding is that such a downcast technically would be undefined behavior.
Another alternative I've considered is to replace inheritance with composition and a reference member, something like:
class Wrapper
{
public:
Base& b;
Wrapper(Base& b_) : b(b_) {}
operator Base&() { return b; }
operator const Base&() const { return b; }
int square() const { return b.x * b.x; }
};
but I'm not sure how that could be done safely since it would open the door for dangling references.