I was looking at std::unordered_map and saw that if I wanted to use a string as the key, I'd have to create a class containing a functor.
Out of curiosity, I was wondering if a lambda could be used in place of this.
Here's the working original:
struct hf
{
size_t operator()(string const& key) const
{
return key[0]; // some bogus simplistic hash. :)
}
}
std::unordered_map<string const, int, hf> m = {{ "a", 1 }};
Here's my attempt:
std::unordered_map<string const, int, [](string const& key) ->size_t {return key[0];}> m = {{ "a", 1 }};
That failed with the following errors:
exec.cpp: In lambda function:
exec.cpp:44:77: error: ‘key’ cannot appear in a constant-expression
exec.cpp:44:82: error: an array reference cannot appear in a constant-expression
exec.cpp: At global scope:
exec.cpp:44:86: error: template argument 3 is invalid
exec.cpp:44:90: error: invalid type in declaration before ‘=’ token
exec.cpp:44:102: error: braces around scalar initializer for type ‘int’
Given the errors, it would seem that the lamba is different enough from a functor that it makes it not a constant expression. Is that correct?
The way to pass the lambda function is:
auto hf = [](string const& key)->size_t { return key[0]; };
unordered_map<string const, int, decltype(hf)> m (1, hf);
^^^^^^^^^^^^ ^^
passing type object
The output of decltype(hf)
is a class type which doesn't have default constructor (it's deleted by =delete
). So, you need pass the object by constructor of unordered_map
to let it construct the lambda object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With