【发布时间】:2021-10-22 19:49:25
【问题描述】:
我正在尝试从我的代码中删除一些重复的代码。因此,有 2 个函数具有几乎相同的代码 Post 和 Send,但它们具有不同数量的参数,这让我认为它应该是可变参数模板或 std::function(如果我错了,请纠正我)。一个函数调用是不同的,所以我认为它应该是指向成员函数的指针,但我不能创建一个指针,因为 send_report 和 publish_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
}
正如我所见,Post 和 Send 应该包含在可变参数模板中,send_report 和 publish_event 应该包含在 std::function 中。你能为我的案例提供一些代码示例吗?我的编译器是 C++11。
【问题讨论】:
-
查看en.cppreference.com/w/cpp/language/lambda底部的示例,了解如何声明
std::functions并将lambdas分配给它们。 -
也许最直接的解决方案是在不同行之前和之后为“相同代码”引入两个私有帮助函数。
-
@IgorTandetnik 那里有条件和周期以及很多其他东西,我最终会重写这两个相同的函数。只更改一个调用更容易,但我无法理解当前如何使用 std::function 和 lamda