mardi 30 novembre 2021

C++: Member function call forwarding using variadic data structure

I am trying to create a class (similar to std::tuple) which can hold a variable number of references to objects of different type and which can forward a call to a specific member function to all of its constituents. Here is an example:

// g++ Test7.C -std=c++17 -o Test7

#include <iostream>

struct P1 { void operator()(void) const { std::cout<<"P1 "; } };
struct P2 { void operator()(void) const { std::cout<<"P2 "; } };
struct P3 { void operator()(void) const { std::cout<<"P3 "; } };

template <class... EmitterList> struct Emitters 
{
 inline void operator()(void) const { std::cout<<std::endl; }
};

template <class Emitter, class... EmitterList>
class Emitters<Emitter,  EmitterList...> : public Emitters<EmitterList...>
{
public:
 using Base = Emitters<EmitterList...>;

 Emitters(const Emitter & e, const EmitterList & ... eList)
  : emitter(e), Base(eList...) {}

 inline void operator()(void) const { emitter(); this->Base::operator()(); }
private:
 const Emitter & emitter;
};

int main(void)
{
 P1 p1;
 P2 p2;
 P3 p3;
 Emitters e0;           e0(); // works
 //Emitters e1{p1};       e1(); // does not work
 //Emitters e2{p1,p2};    e2(); // does not work
 //Emitters e3{p1,p2,p3}; e3(); // does not work
 return 0;
}

The expectation is that e1() would output "P1 \n" (calls p1()), e2() would output "P1 P2 \n" (calls p1(); p2()), and e3() would output "P1 P2 P3 \n" (calls p1(); p2(); p3();). But something is not right in the code: it compiles for e0 but not for the other cases. Could you please help me to understand what I am doing not right here and how to fix it?

Thank you very much for your help!

Aucun commentaire:

Enregistrer un commentaire