是否可以将lambda函数用于模板参数?

时间:2021-10-08 18:53:02

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.

我正在查看std :: unordered_map并看到如果我想使用字符串作为键,我必须创建一个包含仿函数的类。

Out of curiosity, I was wondering if a lambda could be used in place of this.

出于好奇,我想知道是否可以使用lambda来代替这个。

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?

鉴于错误,lamba似乎与仿函数不同,它使得它不是一个常量表达式。那是对的吗?

1 个解决方案

#1


12  

The way to pass the lambda function is:

传递lambda函数的方法是:

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.

decltype(hf)的输出是一个没有默认构造函数的类类型(它被= delete删除)。因此,您需要通过unordered_map的构造函数传递对象,以使其构造lambda对象。

#1


12  

The way to pass the lambda function is:

传递lambda函数的方法是:

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.

decltype(hf)的输出是一个没有默认构造函数的类类型(它被= delete删除)。因此,您需要通过unordered_map的构造函数传递对象,以使其构造lambda对象。