gpt4 book ai didi

c++ - 如何将函数传递给函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:21 26 4
gpt4 key购买 nike

假设我有一个包含 2 个静态函数的类:

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

我有一个 DRY问题是我有 2 个函数,除了它调用的函数外,每一行的代码都完全相同:

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
}

我想删除重复项,理想情况下,做这样的事情:

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

我可以访问 Qt,但不能访问 Boost。有人可以建议我如何重构这样的东西吗?

最佳答案

你可以使用函数指针:

// type of the functions
typedef void Function(Item);

void CommandOne_User() {
// function pointer
Function *func = CommandHandler::command_one;
Refactored_CommandUser(func);
}

void CommandTwo_User() {
// can also be used directly, without a intermediate variable
Refactored_CommandUser(CommandHandler::command_two);
}

// taking a function pointer for the command that should be executed
void Refactored_CommandUser(Function *func) {
// calling the funcion (no explicit dereferencing needed, this conversion is
// done automatically)
func(item);
}

关于c++ - 如何将函数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3026682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com