Home > Enterprise >  C code duplication in functions with different number of arguments
C code duplication in functions with different number of arguments

Time:10-26

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.

CodePudding user response:

Solved it

#include <iostream>
#include <functional>

using namespace std;

class MyClass
{
public:
   void Post( int responseStream );
   void Send();

   void send_report( int responseStream, std::string str );
   void publish_event( std::string str );

   // callbacks
   void process( int );
   void update();
   
   template<typename F>
   void SuperSend( F send_func );
};

template<typename F>
void MyClass::SuperSend( F send_func )
{
    std::string str = "Hello";
    
    // lots of code
    send_func(str);
    // lots of code
}

void MyClass::process( int responseStream )
{
   std::function<void(std::string)> post = [&](std::string n) { send_report(responseStream, n); };
   
   SuperSend( post );
}

void MyClass::update()
{
    std::function<void(std::string)> post = [&](std::string n){ publish_event(n); };
    
    SuperSend( post );
}

void MyClass::send_report( int responseStream, std::string str )
{
    cout << __FUNCTION__ << ": " << str << responseStream << endl;
}
void MyClass::publish_event( std::string str )
{
    cout << __FUNCTION__ << ": " << str << endl;
}

int main()
{
    MyClass A;
    
    A.process(1);
    A.update();
    
    return 0;
}
  • Related