假设我有一个 bool 变量(全局或本地)和一个存在的函数。该函数应仅在 bool 变量为真时执行。由于此函数重复多次,我需要一种方法来执行此函数,而无需执行 bool 变量是否每次都为真。
function();
bool executeFun = true;
if(executeFun){
function();
}
..
if(executeFun){
function();
}
Run Code Online (Sandbox Code Playgroud)
.. 需要在function()每次不检查 bool 的情况下执行。谢谢 :)
将它包装在另一个函数中。
auto perhaps = executeFun ? function : +[](){};
perhaps();
perhaps();
perhaps();
Run Code Online (Sandbox Code Playgroud)
您可以使用检查条件后设置的函数指针:
#include <iostream>
using func_t = void(*)();
int main() {
func_t p = []{};
p(); // does nothing
if(true) p = []{ std::cout << "doing something\n"; };
p(); // does something
}
Run Code Online (Sandbox Code Playgroud)