C++ Weekly - Episode 151 脱水版: C++20's Lambda As Custom Comparators
C++20 中自定义比较式
Episode 94 一集中讲过通过 lambda 自定义比较表达式, 如下:
struct MyData
{
std::string key;
std::string value2;
};
int main()
{
std::set myset{{MyData{"Bob"}}, [](const MyData &lhs, const MyData &rhs) { return lhs.key < rhs.key; }};
}
该代码块在 C++17 中可以正确编译.
在 C++20 中, lambda 支持默认构造, 可存在于未经求值, 我们可以优化这块代码:
std::set<MyData, decltype([](const MyData &lhs, const MyData &rhs) { return lhs.key < rhs.key; })> myset;