18

I get the error

error: call to implicitly-deleted default constructor of '__compressed_pair_elem<(lambda at 
main.cpp:181:16), 1>': _Base1(std::forward<_Tp>(__t)), _Base2() {}

with the following code. What's the mistake I am making and I couldn't understand the error as well.

using namespace std;

auto my_hash = [](vector<int> const& vec){
    size_t seed = vec.size();
    for(auto& i : vec) {
        seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
};

using MySet = unordered_set<vector<int>, decltype(my_hash)>;

int main() {
    vector<int> a{1,2,3};
    MySet s;
    return 0;
}

1 Answer 1

28

Closure types are not default-constructible prior to C++20 (see P0624). You need to pass in an instance of your hasher:

constexpr std::size_t bucket_count = 512;
MySet s{bucket_count, my_hash};

live example on wandbox.org


Alternatively, you can use a good old struct:

struct Hasher {
auto operator()(vector<int> const& vec) const {
    size_t seed = vec.size();
    for(auto& i : vec) {
        seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
}
};

using MySet = unordered_set<vector<int>, Hasher>;

int main() {
    MySet s;
}

live example on wandbox.org

Sign up to request clarification or add additional context in comments.

5 Comments

I am vaguely sad that that change also doesn't make trivial copyable capture lambdas trivial copyable in general.
When all can we not plugin lambda functions as functors directly? I remember we can plugin lambdas directly sometimes(like sort). @vittorio-romeo
@user3285099: when the type of the closure can be deduced
What does closure being deduced mean? I know close in the mathematics but couldn't understand in this context.
[]{} is a lambda expression, which produces a closure (object with operator()). The type of the closure is unique and anonymous, so you have to use decltype to retrieve it. In contexts such as function templates, the type can be deduced from the call site, so decltype is not required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.