Best way to create true wrapper?
Hello,
I'm currently trying to interface an existing (non-modifiable) class to
other code and wondering what's the best way to create the wrappers. Let's
say I have the following code:
----
class Vec {
public:
virtual double& el(int i) = 0;
virtual double el(int i) const = 0;
};
class ThirdpartyVec; // does not inherit from Vec and cannot be changed
void constfunc(const Vec& v) {
cout << "constfunc: " << v.el(0) << endl;
}
void nonconstfunc(Vec& v) {
v.el(0) = 1;
}
class Wrapper : public Vec {
private:
const ThirdpartyVector& inner;
public:
Wrapper(const ThirdpartyVector& _inner) : inner(_inner) {};
virtual double& el(int i) { return ThirdPartyGetRef(inner,i); };
virtual double el(int i) const { return ThirdPartyGetValue(inner,i); };
}
----
Now ideally I would like the user to be able to write
ThirdpartyVector tpv;
constfunc(tpv);
nonconstfunc(tpv);
and the wrapper objects should be created accordingly. As an alternative, I
could imagine providing a wrap() function, so the code could read
ThirdpartyVector tpv;
constfunc(wrap(tpv));
nonconstfunc(wrap(tpv));
However the above approaches cannot work for the call to nonconstfunc, as
C++ does not allow to cast the temporary to a nonconst reference.
Do you know of any good approach to this problem?
Regards,
Jan