Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Forward method calls to embed object without inheritance

Tags:

c++

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.

like image 255
JPC Avatar asked Jul 23 '14 16:07

JPC


1 Answers

#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.

like image 194
Chris Drew Avatar answered Nov 13 '22 00:11

Chris Drew