Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a lambda function for a template parameter?

Tags:

c++

c++11

lambda

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?

like image 205
Adrian Avatar asked May 26 '13 19:05

Adrian


1 Answers

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.

like image 60
masoud Avatar answered Sep 28 '22 06:09

masoud