加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何编写一个不断敲击输出的包装器?

发布时间:2020-12-16 07:17:48 所属栏目:百科 来源:网络整理
导读:基本上,我想要做的是在一些抽象类上使用包装器,然后使用相同的包装器类包装该类的任何成员函数的输出.继续这样做,以便始终包裹所有对象. 喜欢(presudocode) wrapset(1..10) (multiply,2) (divide,3) (plus,5) (inverse) (collect first 10) .unwrap() 除最后
基本上,我想要做的是在一些抽象类上使用包装器,然后使用相同的包装器类包装该类的任何成员函数的输出.继续这样做,以便始终包裹所有对象.

喜欢(presudocode)

wrap<set(1..10)> (multiply,2)
                 (divide,3)
                 (plus,5)
                 (inverse)
                 (collect first 10)
                .unwrap()

除最后一行之外的所有行都输出一些东西.现在似乎意味着更少,但我相信我们可以在其上应用有趣的东西,如:

wrap<someClass> dat;
dat.splitIntoThreads(2)
    (thingA)    .clone()
    (thingB)    (thing1)
    (thingC)    (thing2)
    (thingD)    (thing3)
    .nothing()  (thing4)
    .sync()     .exit()
    .addMerge()

这是我的包装代码:

template<class T>
struct wrap{
  wrap(){}
  wrap(T b){a=b;}
  template<class L,class...R>
  L operator() (L(T::*f)(R...),R...r){
    return a.f(r...);
  }
  T a;
};

int main(){
  wrap<testClass> a;
  a(&testClass::f,13,'a');
}

它正在工作(gcc,c 0x).但是当我用以下内容替换第6,7行时(实际包装结果)

wrap<L> operator() (L(T::*f)(R...),R...r){
  return wrap<L>(a.f(r...));

编译器只是sais:创建指向非类型“int”的成员函数的指针.

我怎样才能解决这个问题?有没有比这更好的了?继承是一种方式,但由于我们可能在一个包装中有变量实例,我认为它没用.

编辑

这是我的测试课

struct testClass{
  int f(int a,char b){
    return a+b;
  }
};

我使用wrap L而不是wrap T的原因是返回类型可能并不总是T.

解决方法

你可以尝试这样的事情:

#include <iostream>
#include <type_traits>

template<class T,bool = false>
struct wrap{
  template <typename... Args>
  wrap(Args&&... args) : a{std::forward<Args>(args)...} {};
  template<class L,class...R>
  wrap<L,std::is_fundamental<L>::value> operator() (L(T::*f)(R...),R...r){
    return wrap<L,std::is_fundamental<L>::value > {(a.*f)(r...)};
  }
  T a;
};

template<class T>
struct wrap <T,true>{
  template <typename... Args>
  wrap(Args&&... args) : a{std::forward<Args>(args)...} {}
  template<class L,std::is_fundamental<L>::value> operator() (L(*f)(T a,R...),R...r){
      return wrap<L,std::is_fundamental<L>::value > {f(a,r...)};
  }
  T a;
};

class testClass {
    int m;
public:
testClass(int _m) : m{_m}{}
    int multiAdd(int x,char y) {
        m += x + y;
        return m;
    }
};

int add(int a,char b)
{
    return a+b;
}

int main(){
  wrap<testClass> a{0};
  std::cout << a(&testClass::multiAdd,'d')(add,'a').a<<std::endl;

  wrap<int,true> b{3};
  std::cout << b(add,'a').a<<std::endl;
}

cpp.sh/6icg

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读