w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How can I avoid this code duplication?

Use 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();
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.