vendredi 22 octobre 2021

C++ code duplication in functions with different number of arguments

I'm trying to remove some code duplication from my code. So there are 2 functions with almost the same code Post and Send but they have different number of parameters which puts me on thought that it should be or variadic template or std::function (correct me if I'm wrong). One function call is different though so I'm thinking it suppose to be pointer to member function, but I cannot make a pointer as send_report and publish_event functions also have different number of parameters.

So here's pseudocode

class MyClass
{
   void Post( CStream& responseStream );
   void Send();

   void send_report( CStream& responseStream, std::string );
   void publish_event( std::string string );

   // callbacks
   void process( CStream& responseStream );
   void update();
}

void MyClass::Post( CStream& responseStream )
{
// ... the same code ...
      send_report( responseStream, string ); // different function
// ... the same code ...
}

void MyClass::Send()
{
// ... the same code ...
      publish_event( string ); // different function
// ... the same code ...
}

void MyClass::process( CStream& responseStream )
{
   // some code
   Post( responseStream );
}

void MyClass::update()
{
   // some code
   Send();
}

void MyClass::send_report( CStream& responseStream, std::string )
{
// differ
}
void MyClass::publish_event( std::string string )
{
// differ
}

As I see it Post and Send should be wrapped in variadic template and send_report and publish_event are wrapped into std::function. Could you provide me with some code example for my case? My compiler is C++11 though.

Aucun commentaire:

Enregistrer un commentaire