Search code examples
c++templatespredicatestd-function

How to properly use std::function as a predicate


I want to use std::function as a predicate in a templated helper function but I get an error:

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

I don't understand what I'm doing wrong.


Solution

  • Correct Code:

    #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. You need to specify template argument (Any)
    2. You forgot to add return type of lambda