如何解决C++ std::map `emplace` 和 `emplace_back` 重载
我的问题如下:
我有一对函数:
using my_map_t = std::map<int,double>;
using my_map_iterator_t = my_map_t::iterator;
my_map_t my_map;
...
void func1(int a,double b) {
...
my_map.emplace(a,b);
...
}
void func2(int a,double b,my_map_iterator_t hint) {
...
my_map.emplace_hint(hint,a,b)
...
}
我想避免代码重复并尽可能快。我发现的一种可能的解决方案是以下
template <bool has_hint>
func(int a,my_map_iterator_t hint=my_map.end() /*unused if has_hint=false*/) {
...
if constexpr(has_hint)
my_map.emplace_hint(hint,b);
else
my_map.emplace(a,b);
...
}
但不幸的是,我在目标机器上没有 c++17 编译器。
我正在考虑为提示使用默认参数,这样 emplace_hint
将具有与 emplace
完全相同的效果。但是我想象地图被实现为(RB)树,因此所需的迭代器将被计算每一个(可能作为“中值迭代器”)
你能建议我一个优雅的出路吗?
解决方法
您可以使用通用方法进行因式分解:
template <typename F>
void func_impl(int a,double b,F emplacer)
{
// ...
emplacer(my_map,a,b);
// ...
}
void func1(int a,double b) {
func_impl(a,b,[](auto& my_map,int a,double b) { my_map.emplace(a,b); });
}
void func2(int a,my_map_iterator_t hint) {
func_impl(a,[&hint](auto& my_map,double b) { my_map.emplace_hint(a,hint); });
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。