Variation pattern

So, I am trying to use variable templates to create objects from more convenient subtypes, but I am having problems in doing exactly what I want.

template<class ...Functor>
struct SeqMethod:public Functor...{
  template<class F>
  void call(F& a){
    F::operator()();
  }
  template<class F,class ... funcs>
  void call(){
    F::operator()();

    call<funcs...>();
  }
  public:
  void operator()(){
    call<Functor...>();
  }
};

This is not valid syntax, so there.

Ideally, I would like to use something like this

class A{
public:
  void operator()(){
    std::cout<<"A";
  }
};
class B{
public:
  void operator()(){
    std::cout<<"B";
  }
};

class C:public SeqMethod<A,B>{};

Which in this case should output "AB", and is generally suitable for compiling behavior together.

+4
source share
2 answers

The easiest way to do this is with C ++ 17 to collapse expressions :

template<class ...Functor>
struct SeqMethod:public Functor...{

 public:
    void operator()(){
        (Functor::operator()(),...);
    }
};

class A{
public:
    void operator()(){
        std::cout<<"A";
    }
};
class B{
public:
    void operator()(){
        std::cout<<"B";
    }
};

class C:public SeqMethod<A,B>{};

int main()
{
    C c;
    c();
    return 0;
}

Output (checked with gcc 6.2):

AB
+2
source

- call .
++ 11/++ 14:

template<class ...Functor>
struct SeqMethod:public Functor...{
  public:
  void operator()(){
      int _[] = { (Functor::operator()(), 0)... };
      return void(_);
  }
};

:

#include<iostream>

template<class ...Functor>
struct SeqMethod:public Functor...{
  public:
  void operator()(){
    int _[] = { (Functor::operator()(), 0)... };
    return void(_);
  }
};

class A{
public:
  void operator()(){
    std::cout<<"A";
  }
};
class B{
public:
  void operator()(){
    std::cout<<"B";
  }
};

class C:public SeqMethod<A,B>{};

int main() {
  C c;
  c();
}
+4

Source: https://habr.com/ru/post/1664731/


All Articles