I'm wondering if it's possible to automatically forward a method call to an embedded object, without inheritance. For instance:
class embed
{
public:
void embed_method() {return};
};
class container
{
public:
void container_method() {return;}
private:
embed obj;
};
int main()
{
container object;
object.container_method(); // Local method call
object.embed_method(); // 'Forward' call, obviously doesn't work
}
It could be very useful when inheriting from a base class is not possible / not recommended.
Currently, the only choice I have is to manually rewrite embed
class methods into container
class, and then call embed
methods from container
ones. Even if the process can be scripted, it's still annoying and it seems to be a bad solution.
#include <utility>
class Embed {
public:
void embedMethod() { }
};
class Container {
private:
Embed embed;
public:
void containerMethod() {}
template<typename ...Args, typename R>
R forward( R (Embed::* function)(Args...), Args &&...args) {
return (embed.*function)(std::forward<Args>(args)...);
}
};
int main() {
Container c;
c.containerMethod();
c.forward(&Embed::embedMethod);
}
Live demo.
I'm not condoning the design, it is very poor encapsulation.
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