lundi 28 décembre 2015

A function with a std::function parameter does not accept a lamba function

I am trying to get more familiar with the C++11 standard by implementing the std::iterator on my own doubly linked list collection and also trying to make my own sort function to sort it.

I would like the sort function to accept a lamba as a way of sorting by making the sort accept a std::function, but it does not compile (I do not know how to implement the move_iterator, hence returning a copy of the collection instead of modifying the passed one).

template <typename _Ty, typename _By>
LinkedList<_Ty> sort(const LinkedList<_Ty>& source, std::function<bool(_By, _By)> pred)
{
    LinkedList<_Ty> tmp;
    while (tmp.size() != source.size())
    {
        _Ty suitable;
        for (auto& i : source) {
            if (pred(suitable, i) == true) {
                correct = i;
            }
        }
        tmp.push_back(suitable);
    }
    return tmp;
}

Is my definition of the function wrong? If I try to call the function, I recieve a compilation error.

LinkedList<std::string> strings{
    "one",
    "two",
    "long string",
    "the longest of them all"
};

auto sortedByLength = sort(strings, [](const std::string& a, const std::string& b){
    return a.length() < b.length();
});

Error: no instance of function template "sort" matches the argument list argument types are: (LinkedList, lambda []bool (const std::string &a, const std::string &)->bool)

Aucun commentaire:

Enregistrer un commentaire