C++ 如何简化仅函数调用不同的成员函数

qua*_*ant 3 c++ function simplify

我需要创建 10 个函数,这些函数非常长并且除了每个函数中的一行代码之外在各个方面都相同。这行代码是一个函数调用。有没有办法将其压缩为一个函数?前任。

int doSomethingOne()
{
...
one();
...
}

int doSomethingtwo()
{
... // same as one
two();
... // same as one
}
Run Code Online (Sandbox Code Playgroud)

Ted*_*gmo 5

您可以创建一个函数模板来执行所有常见部分并在其中调用用户提供的函数:

#include <iostream>

template <class Func>
int doSomething(Func&& func) {
    // do all the common stuff before calling func
    func();
    // do all the common stuff after calling func
    return 0;
}

void one() { std::cout << "One\n"; }
void two() { std::cout << "Two\n"; }

int doSomethingOne() { return doSomething(&one); }
int doSomethingtwo() { return doSomething(&two); }

int main() {
    doSomethingOne();
    doSomethingtwo();
    doSomething(+[]{ std::cout << "Anything goes\n"; });
}
Run Code Online (Sandbox Code Playgroud)

输出:

One
Two
Anything goes
Run Code Online (Sandbox Code Playgroud)