使用模板将 lambda 解析为函数

Parsing lambda to a function using templates

本文关键字:函数 lambda      更新时间:2023-10-16

我对C++很陌生,我目前正在尝试学习如何将模板用于lambda函数。

lambda 可以在 main 函数中看到,它只是进行布尔检查。

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

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

我希望有一个可以实现,我可以利用如下所示的模板,但我无法获得任何工作。

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

有没有一种通用的方法可以使用 lambda 模板?

不要将模板参数包装在 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; }); 
}

好处超过std::function .

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