如何正确使用 std::function 作为谓词

How to properly use std::function as a predicate

本文关键字:function 谓词 std 何正确      更新时间:2023-10-16

我想在模板化辅助函数中使用 std::function 作为谓词,但出现错误:

main.cpp(15): error C2672: 'Any': no matching overloaded function found
main.cpp(15): error C2784: 'bool Any(const std::vector<T,std::allocator<_Ty>> &,const std::function<bool(const T &)>)': could not deduce template argument for 'const
std::function<bool(const T &)>' from 'main::<lambda_1b47ff228a1af9c86629c77c82b319f9>'
main.cpp(7): note: see declaration of 'Any'
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
template <typename T>
bool Any(const std::vector<T>& list, const std::function<bool(const T&)> predicate)
{   
return std::any_of(list.begin(), list.end(), [&](const T& t) { return predicate(t); });
}
int main()
{
auto myList = std::vector<int>{ 1, 2, 3, 4, 5 };
if (Any(myList, [](int i) { return i % 5 == 0; }))
{
std::cout << "Bingo!" << std::endl;
}
else
{
std::cout << "Not found :(" << std::endl;
}
return 0;
}

我不明白我做错了什么。

我不明白我做错了什么。

您正在将 lambda 传递给Any,但隐式转换(从 lambda 到std::function(不会在模板参数推导中考虑,这使得无法在第二个函数参数上推断T

类型

推断不考虑隐式转换(上面列出的类型调整除外(:这是重载解决的工作,稍后会发生。

您可以使用std::type_identity(自 C++20 起(从推导中排除第二个参数;然后模板参数T将仅在第一个参数上推导,然后代码工作正常。

template <typename T>
bool Any(const std::vector<T>& list, const std::function<bool(const std::type_identity_t<T>&)> predicate)
//                                                                  ^^^^^^^^^^^^^^^^^^^^^^^
{   
return std::any_of(list.begin(), list.end(), [&](const T& t) { return predicate(t); });
}

如果你不能申请C++20,你可以参考上面的链接页面,它给出了一个可能的实现,实现你自己的type_identity并不难。如果你不坚持std::function,你可以为谓词添加另一个模板参数。

template <typename T, typename P>
bool Any(const std::vector<T>& list, P predicate)
{   
return std::any_of(list.begin(), list.end(), predicate);
}

或者使其更通用地使用其他容器或原始数组。

template <typename C, typename P>
bool Any(const C& c, P predicate)
{   
return std::any_of(std::begin(c), std::end(c), predicate);
}

正确的代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
template <typename T>
bool Any(const std::vector<T>& list, const std::function<bool(const T&)> predicate)
{   
return std::any_of(list.begin(), list.end(), [&](const T& t) { return predicate(t); });
}
int main()
{
auto myList = std::vector<int>{ 1, 2, 3, 4, 5 };
if (Any<int>(myList, [](int i) -> bool { return i % 5 == 0; }))
{
std::cout << "Bingo!" << std::endl;
}
else
{
std::cout << "Not found :(" << std::endl;
}
return 0;
}

if (Any<int>(myList, [](int i) -> bool { return i % 5 == 0; }))

  1. 您需要指定模板参数(任何(
  2. 您忘记添加 lambda 的返回类型