将 std::function 作为参数传递给for_each

passing std::function as a parameter to for_each

本文关键字:for 参数传递 each std function      更新时间:2023-10-16
#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);
}   

我正在尝试将sample_function((传递给for_each但是遇到了此错误

错误 C2197 'std::函数 ':调用的参数过多

我认为您想要的是以下内容

#include <iostream>
#include <vector>
#include <functional>
std::function<void(int)> sample_function =  [](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);
}

输出为

10 15 20 25 35 45 50

或者,如果您确实想定义一个返回类型 std::function 对象的函数,那么您可以编写

#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() );
                                                                ^^^^
你需要

括号来唤起对sample_function的函数调用,而函数调用又会为你for_each返回std::function对象:

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

现场演示