首页 > 解决方案 > How can I pass a condition to a function in C++?

问题描述

I would like to have a function that runs some code until a given condition is met. How can I pass a function to a function such that the end function calls the parameter function over and over until it outputs a given value? Given that I will not be reusing the parameter function, I would prefer to not create a named function if possible.

标签: c++

解决方案


这是一个简短的例子。创建一个以 lambda 作为参数的函数。

template<typename Func>
void myFunction(Func&& lambda){
    int i=1;
    while (lambda(i++)){
        std::cout << "Still running!\n";
    }
}

使用 lambda 作为参数调用函数

int main(){
      myFunction([](auto&& val){ return val < 4 ;}); 
      return 0;
    }

推荐阅读