Search code examples
c++templates

Summarizing similar functions into one in C++


Let's say I have the following toy problem class:

class A {
  public:
    // ...
    void setID(B* b, unsigned int ID);
    void setName(B* b, string name);
    void setNumber(B* b, unsigned int num);
    // ...
};

where

void A::setID(B* b, unsigned int ID) {
  foo(b);
  b->doSomethingWithID(ID);
  bar(b);
}

void A::setName(B* b, string name) {
  foo(b);
  b->doSomethingWithName(name);
  bar(b);
}

void A::setNumber(B* b, int num) {
  foo(b);
  b->doSomethingWithNum(num);
  bar(b);
}

In my real problem, the foo() and bar() functions are quite complex, and I have several of those setter routines. However, each of the setter routines calls foo(), a member-function of the B object, and bar().

Is there a possibility of writing just one generic function set() that I can pass the function that shall be executed on b to reduce the amount of copied code?


Solution

  • Write a helper function.

    template <typename FN>
    void myHelper(B *b, FN fn) {
       foo(b);
       fn();
       bar(b);
    }
    

    You'd then call like so:

    void A::setID(B* b, unsigned int ID) {
      myHelper(b, [b, ID]() { b->doSomethingWithID(ID); });
    }