遍历参数包
Iterating over a parameter pack
我有一个参数包 args...
任意类型的向量,对应的有一个索引向量说 v = {3,0,5...}
具有相同的大小,并且顺序与 args...
。我想要 get_tuple
到 return 在 v
.
给出的索引处的 args...
元素的元组
这是我目前所拥有的,但我一直在尝试迭代参数包的成员。
template<typename... Args>
auto get_tuple(const std::vector<size_t>& vector, const Args &... args) {
return std::make_tuple(args[v[0]]...);
}
例如:
std::vector<std::string> v1 = {"a", "b"};
std::vector<int> v2 = {1,2};
std::vector<size_t> v = {0,1};
auto result = get_tuple(v, v1, v2); // ("a",2) expected
在 C++17 中,您需要额外的间接级别来获取一组索引以获取这些索引处的一组元素:
template<typename... Args, std::size_t... Is>
auto get_tuple_impl(const std::vector<std::size_t>& indices,
std::index_sequence<Is...>,
const Args&... args) {
return std::make_tuple(args[indices[Is]]...);
}
template<typename... Args>
auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) {
return get_tuple_impl(indices, std::index_sequence_for<Args...>(), args...);
}
在 C++20 中,我们可以为您提供调用模板参数的 lambda 函数 in-place:
template<typename... Args>
auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) {
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
return std::make_tuple(args[indices[Is]]...);
}(std::index_sequence_for<Args...>());
}
您可能还想添加断言 assert(indices.size() == sizeof...(Args));
或改用 std::array<std::size_t, N>
类型。
我有一个参数包 args...
任意类型的向量,对应的有一个索引向量说 v = {3,0,5...}
具有相同的大小,并且顺序与 args...
。我想要 get_tuple
到 return 在 v
.
args...
元素的元组
这是我目前所拥有的,但我一直在尝试迭代参数包的成员。
template<typename... Args>
auto get_tuple(const std::vector<size_t>& vector, const Args &... args) {
return std::make_tuple(args[v[0]]...);
}
例如:
std::vector<std::string> v1 = {"a", "b"};
std::vector<int> v2 = {1,2};
std::vector<size_t> v = {0,1};
auto result = get_tuple(v, v1, v2); // ("a",2) expected
在 C++17 中,您需要额外的间接级别来获取一组索引以获取这些索引处的一组元素:
template<typename... Args, std::size_t... Is>
auto get_tuple_impl(const std::vector<std::size_t>& indices,
std::index_sequence<Is...>,
const Args&... args) {
return std::make_tuple(args[indices[Is]]...);
}
template<typename... Args>
auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) {
return get_tuple_impl(indices, std::index_sequence_for<Args...>(), args...);
}
在 C++20 中,我们可以为您提供调用模板参数的 lambda 函数 in-place:
template<typename... Args>
auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) {
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
return std::make_tuple(args[indices[Is]]...);
}(std::index_sequence_for<Args...>());
}
您可能还想添加断言 assert(indices.size() == sizeof...(Args));
或改用 std::array<std::size_t, N>
类型。