c++ - 我怎样才能避免这种代码重复?

标签 c++ refactoring stdbind

我有两个方法,除了它们调用的两个方法(以及我可以轻松参数化的其他一些细节)之外,它们的代码几乎相同。但是,这些方法调用具有相同的签名,因此我认为我可以将它们概括为一个方法。

class A{
    IApi* m_pApi;
    void M1();
    void M2();
public:
    void DoThings();
}

void A::M1(){
    int i;
    bool b;    
    m_pApi->method1( &i, &b );    
    //Other stuff...
}

void A::M2(){
    int i;
    bool b;    
    m_pApi->method2( &i, &b );
    //Other stuff...
}

void A::DoThings(){
    M1();
    M2();
}

我知道如何“参数化”“其他内容”代码,但问题是对 method1method2 的调用。我想我必须以某种方式使用 std::bind,但我不能做这样的事情......

void A::M( std::function<void(int*,bool*)> f ){
    int i;
    bool b;
    f( &i, &b );
}

void A::DoThings(){
    M( std::bind( ???, m_pApi ) ); //M1
    M( std::bind( ???, m_pApi ) ); //M2
}

这里的问题是m_pApi不是一个具体类(它是由一堆具体类实现的接口(interface)),所以我不确定我是否可以做通常的&Class::方法 东西。有什么建议吗?

最佳答案

使用pointers to member function .

#include <iostream>
using namespace std;

struct IApi {
    void method1(int * i, bool * b) {
        *i = 1; *b = true;
    }
    void method2(int * i, bool * b) {
        *i = 2; *b = false;
    }
};

class A {
    IApi* m_pApi;
    void M(void (IApi::*)(int*, bool*));
public:
    A() : m_pApi(new IApi()) {}
    void DoThings();
};

void A::M(void (IApi::*mptr)(int*, bool*)) {
    int i;
    bool b;    
    (m_pApi->*mptr)( &i, &b );    
    cout << i << ' ' << b << endl;
}

void A::DoThings(){
    M(&IApi::method1);
    M(&IApi::method2);
}

int main() {
    A a;
    a.DoThings();
}

关于c++ - 我怎样才能避免这种代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962458/

相关文章:

c++ - 我的特定应用程序的 memcpy 或 std::copy

c++ - 使用 basic_string 声明新的字符串类型

c# - 如何在一个方法调用中创建文件及其父目录?

c# - 如何编写一个公开公共(public)命名空间的命名空间,以避免在 C#.NET 中使用多个 using 语句

c++11 - 将函数向量的参数传递给 std::function 时出现问题

c++ - 指向其他 vector 元素的指针的 vector

c++ - 如何从 Node.js 调用 C++ 代码?

java - 错误 : Could not find or load main class cucumber. cli.Main

c++ - 无法将 std::bind 返回值分配给 std::function

c++ - std::bind 头文件声明