我一直在实现我的 std::map
版本,以便从内部更好地了解事物的工作原理。在实现 std::map::emplace()
时,我遇到了一个问题。
所以,我的函数签名如下所示:
template <typename Key, typename Value>
template <typename ... Args1, typename ... Args2>
std::pair<typename Map<Key, Value>::Iterator, bool> Map<Key, Value>::emplace(
std::piecewise_construct_t pwc,
std::tuple<Args1...> first_args,
std::tuple<Args2...> second_args);
在实际放置之前,我确实需要从 first_args
构造键,以便比较树中的键。我已经尝试了一些事情,但无法找出正确的方法来做到这一点。据我了解,它应该看起来像这样:
Key k(std::get<sizeof...(Args1)>(std::forward<Args1>(first_args));
问题是,对于元组的每个元素,std::get()
应该接收一个不同的数字作为其模板参数(这样元组的正确元素将被传递到正确的地方)。
我见过有人通过将大小作为模板参数并将 std::index_sequence
作为参数之一传递来解决这个问题,但是 std::map::emplace()
没有任何这种方法,所以应该有一种方法可以在没有这种情况的情况下实现放置。
提前致谢。任何建议将不胜感激!
最佳答案
I've seen people solve this problem by having size as template parameter and passing std::index_sequence as one of parameters, but std::map::emplace() does not have any of this approach, so there should be a way to do implement emplacing without this.
std::map::emplace()
是真的没有收到 std::index_sequence
,但我不知道是否在内部创建一个 std::index_sequence
并调用辅助函数来正确管理元组。
换句话说,你可以这样写
Key k { make_object_from_tuple<Key>(first_arg, std::index_sequence_for<Args1...>{}) };
内部make_object_from_tuple()
你可以使用 std::index_sequence
从元组中提取元素并构造 Key
对象。
换句话说:根据 Kerndog73 的建议,您可以复制 std::make_from_tuple_impl()
在 this page 中实现.
如果您不想开发新功能,可以使用 std::pair
中的分段构造函数.
没有什么能迫使你构建一个 std::pair<Key, Value>
: 如果你想先构造一个 Key
并且,仅在必要时,接下来是 Value
, 你可以在 std::pair<Key, int>
之前构造在(在这种情况下)a std::pair<Value, int>
之后.
我的意思是...您可以创建 Key
没有 Value
std::tuple<int> ti{0};
Key k { std::pair<Key, int>{std::piecewise_construct_t, first_args, ti).first };
之后,只有在您需要时,Value
Value v { std::pair<Value, int>{std::piecewise_construct_t, second_args, ti).first };
关于c++ - 将带有可变参数模板参数的 std::tuple 作为其元素类型传递给另一个函数作为参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56746602/