C ++ Forward方法调用嵌入没有继承的对象 [英] C++ Forward method calls to embed object without inheritance

查看:153
本文介绍了C ++ Forward方法调用嵌入没有继承的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以自动将方法调用转发到嵌入式对象无继承。例如:

 类嵌入
{
public:
void embed_method };
};

类容器
{
public:
void container_method(){return;}
private:
embed obj;
};

int main()
{
容器对象;

object.container_method(); //本地方法调用
object.embed_method(); //'Forward'call,显然不工作
}

当从基类继承不可能/不推荐时有用。
目前,我唯一的选择是手动将 embed 类方法重写为 container 类,然后从 container 调用 embed 方法。即使这个过程可以脚本化,它仍然很烦人,似乎是一个坏的解决方案。

解决方案

  #include< utility> 

类嵌入{
public:
void embedMethod(){}
};

类容器{
private:
嵌入;
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);
}

现场演示



我不允许设计,封装非常差。 >

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.

这篇关于C ++ Forward方法调用嵌入没有继承的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆