将可变迭代器参数转换为值类型的元组

convert variadic iterator arguments to tuple of value types

本文关键字:类型 元组 转换 迭代器 参数      更新时间:2023-10-16

如何将IteratorTypes的模板参数包转换为相应value_type的元组?我尝试了以下操作,但失败了

error: wrong number of template arguments (2, should be 1)
using ValueTypes = typename std::iterator_traits<IteratorTypes...>::value_type;
                                                                              ^

#include <type_traits>
#include <vector>
#include <tuple>
template <typename ... IteratorTypes>
void foo(IteratorTypes&&...its)
{
    using ValueTypes = typename std::iterator_traits<IteratorTypes...>::value_type;
    static_assert(std::is_same<std::tuple<ValueTypes>,std::tuple<int,float>>::value, "types do no match");
}
int main() {
    std::vector<int> int_vec(1);
    std::vector<float> float_vec(1);
    foo(int_vec.begin(), float_vec.begin());
    return 0;
}

在coliru 上直播

...紧跟在要展开的模式之后。

using ValueTypes = std::tuple<typename std::iterator_traits<IteratorTypes>::value_type...>;
static_assert(std::is_same<ValueTypes, std::tuple<int,float>>::value, "types do no match");

此外,在将其传递给iterator_traits之前,您可能应该先std::decay IteratorTypes,或者按值而不是通过转发引用获取它们。

。。。或者为了更容易阅读:

#include <type_traits>
#include <vector>
#include <tuple>
#include <utility>
template <typename ... IteratorTypes>
void foo(IteratorTypes&&...its)
{
    using value_type_tuple = std::tuple<typename IteratorTypes::value_type...>;
    using desired_tuple = std::tuple<int, float>;
    static_assert(std::is_same<value_type_tuple , desired_tuple>::value, "types do no match");
}
int main() {
    std::vector<int> int_vec(1);
    std::vector<float> float_vec(1);
    foo(int_vec.begin(), float_vec.begin());
    return 0;
}