【发布时间】:2018-01-08 17:25:21
【问题描述】:
我想用 lambda 比较器构造一个集合。
由于已知的限制,您不能将 lambda 指定为模板参数(您需要 decltype() 它)所以我考虑在模板参数列表中指定映射的键并在构造函数参数中指定比较器。
比如:
std::set<Color> colors({ { "Red", 255, 0 , 0 }, { "Green", 0,255,0 }, { "Black", 0,0,0 } } , [](const Color& a, const Color& b){return a.name()<b.name();});
但是根据我从错误消息中了解到的信息,我一指定模板参数(<Color>)就强迫其他人默认(std::less 用于比较器)。而且仅采用比较器的映射构造函数不够聪明,无法从比较器参数中获取 Key 类型,也就是这不起作用:
std::set colors([](const Color& a, const Color& b){return a.name()<b.name();});
有没有办法指定我想要一组Colors,但是让构造函数指定比较器。
请注意,从 C++17 开始,我可以使用构造函数来推导模板类型,但这并不漂亮,因为我需要编写的东西比我想要的要多。
std::set colors(std::initializer_list<Color>{ { "Red", 255, 0 , 0 }, { "Green", 0,255,0 }, { "Black", 0,0,0 } } , [](const Color& a, const Color& b){return a.name()<b.name();}, std::allocator<char/*???*/>{});
完整代码here:
【问题讨论】:
标签: c++ templates stl c++17 template-argument-deduction