c++ - How can I avoid this code duplication? -
i have 2 methods have same code except 2 methods call (and other details can parameterize). however, method calls have same signature, think can generalize them single method.
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(); }
i can figure out how "parameterize" "other stuff" code, problem calls method1
, method2
. think have use std::bind
somehow, can't this...
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 }
the problem here m_papi
not concrete class (it's interface implemented bunch of concrete classes), i'm not sure if can usual &class::method
thing. suggestions?
#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 { 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 << << ' ' << b << endl; } void a::dothings(){ m(&iapi::method1); m(&iapi::method2); } int main() { a; a.dothings(); }
Comments
Post a Comment