【问题标题】:C++ code duplication in functions with different number of arguments具有不同数量参数的函数中的 C++ 代码重复
【发布时间】:2021-10-22 19:49:25
【问题描述】:

我正在尝试从我的代码中删除一些重复的代码。因此,有 2 个函数具有几乎相同的代码 PostSend,但它们具有不同数量的参数,这让我认为它应该是可变参数模板或 std::function(如果我错了,请纠正我)。一个函数调用是不同的,所以我认为它应该是指向成员函数的指针,但我不能创建一个指针,因为 send_reportpublish_event 函数也有不同数量的参数。

所以这里是伪代码

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
}

正如我所见,PostSend 应该包含在可变参数模板中,send_reportpublish_event 应该包含在 std::function 中。你能为我的案例提供一些代码示例吗?我的编译器是 C++11。

【问题讨论】:

  • 查看en.cppreference.com/w/cpp/language/lambda底部的示例,了解如何声明std::functions并将lambdas分配给它们。
  • 也许最直接的解决方案是在不同行之前和之后为“相同代码”引入两个私有帮助函数。
  • @IgorTandetnik 那里有条件和周期以及很多其他东西,我最终会重写这两个相同的函数。只更改一个调用更容易,但我无法理解当前如何使用 std::function 和 lamda

标签: c++ c++11


【解决方案1】:

解决了

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多