C++ 将std::function作为参数传递给每个 #包括 #包括 #包括 #包括 #包括 std::函数示例_函数() { 返回 [](int x)->void { 如果(x>5) std::cout

C++ 将std::function作为参数传递给每个 #包括 #包括 #包括 #包括 #包括 std::函数示例_函数() { 返回 [](int x)->void { 如果(x>5) std::cout,c++,algorithm,vector,foreach,lambda,C++,Algorithm,Vector,Foreach,Lambda,您需要括号来调用sample\u function的函数调用,然后它将返回std::function对象作为for\u each: #include <initializer_list> #include <iostream> #include <algorithm> #include <vector> #include <functional> std::function<void(int)> sample_functi

您需要括号来调用
sample\u function
的函数调用,然后它将返回
std::function
对象作为
for\u each

#include <initializer_list>
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
    return
        [](int x) -> void
    {
        if (x > 5)
            std::cout << x;
    };
}

int main()
{
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function);
}   
std::函数示例_函数(){
返回[](整数x)->void{

如果(x>5)std::cout我想你想要的是

std::function<void(int)> sample_function() {
  return [](int x) -> void {
     if (x > 5) std::cout << x;
  };
}

int main() {
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function());
                                                                 ^^
} 
或者,如果您确实想要定义一个返回类型为
std::function
的对象的函数,那么您可以编写

10 15 20 25 35 45 50

此代码不会将
std::function
传递给
for each
。它传递
sample\u function
,这是一个不带参数并返回类型为
std::function
的对象的函数。错误消息是正确的:
sample\u function
不带参数,因此无法使用范围元素调用。
10 15 20 25 35 45 50
#include <iostream>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
    return  [](int x)
            {
                if (x > 5)  std::cout << x << ' ';
            };
}


int main()
{
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function() );
}
    std::for_each(numbers.begin(), numbers.end(), sample_function() );
                                                                ^^^^