How to pass a function to a function?

Posted by ShaChris23 on Stack Overflow See other posts from Stack Overflow or by ShaChris23
Published on 2010-06-11T22:37:11Z Indexed on 2010/06/11 22:42 UTC
Read the original article Hit count: 171

Filed under:
|
|

Suppose I have a class with 2 static functions:

class CommandHandler
{
public:
  static void command_one(Item);
  static void command_two(Item);
};

I have a problem DRY problem where I have 2 functions that have the exact same code for every single line, except for the function that it calls:

void CommandOne_User()
{
  // some code A

  CommandHandler::command_one(item);

  // some code B
}

void CommandTwo_User()
{
  // some code A

  CommandHandler::command_two(item);

  // some code B
}

I would like to remove duplication, and, ideally, do something like this:

void CommandOne_User()
{
  Function func = CommandHandler::command_one();

  Refactored_CommandUser(func);
}

void CommandTwo_User()
{
 Function func = CommandHandler::command_one();

 Refactored_CommandUser(func);
}

void Refactored_CommandUser(Function func)
{
  // some code A

  func(item);
}

I have access to Qt, but not Boost. Could someone help suggest a way on how I can refactor something like this?

© Stack Overflow or respective owner

Related posts about c++

Related posts about qt