使用模板将lambda解析为函数

Jak*_*o06 1 c++ lambda templates

我是C ++的新手,目前正在尝试学习如何将模板用于lambda函数。

lambda可以在main函数中看到,并且只需进行布尔检查即可。

下面的实现有效,但是我必须在函数中明确声明lambda的类型testing,如输入参数所示。

void testing(std::function<bool(const int& x)> predicate){
    auto a = predicate(2);
    std::cout << a << "\n";
}

int main() {
    int ax = 2;
    testing([&ax](const int& x) { return x == ax;});
}
Run Code Online (Sandbox Code Playgroud)

我希望实现一个可以利用如下所示的模板的实现,但是我什么也无法工作。

template <typename T>
void testing(std::function<bool(const T& x)> predicate){
    auto a = predicate(2);
    std::cout << a << "\n";
}
Run Code Online (Sandbox Code Playgroud)

有没有通用的方法可以将模板用于lambda?

J. *_*rez 5

不要将template参数包装在中std::function

将lambda传递给函数的最好方法是将其作为不受约束的模板参数:

template<class F>
void testing(F predicate) {
    auto a = predicate(2); 
    std::cout << a << '\n';
}

int main() {
    int ax = 2;
    testing([ax](int x) { return x == ax; }); 
}
Run Code Online (Sandbox Code Playgroud)

好处多于std::function

  • std::function 在堆上分配空间以存储函子
  • std::function 具有类似于虚拟函数调用的开销
  • std::function 不能由编译器内联,但是内联直接传递的lambda是微不足道的