如何将std :: array转换为一个点?

时间:2021-04-07 19:19:13

I want to build a template function to convert std::array to a general point which has a constructor accepting its coordinate arguments.

我想构建一个模板函数来将std :: array转换为一个通用点,它有一个构造函数接受它的坐标参数。

template<typename PointT, size_t N>
PointT to(std::array<double, N> const& a)
{
    return PointT(a[0], a[1], ...); // How to expand a?
}

My question is: is there a way to expand the array a?

我的问题是:有没有办法扩展数组?

1 个解决方案

#1


7  

template <typename PointT, std::size_t N, std::size_t... Is>
PointT to(std::array<double, N> const& a, std::index_sequence<Is...>)
{
    return PointT(a[Is]...);
}

template <typename PointT, std::size_t N>
PointT to(std::array<double, N> const& a)
{
    return to<PointT>(a, std::make_index_sequence<N>{});
}

DEMO


Note: index_sequence/integer_sequence utilities are available starting from C++14. Since the question is tagged as C++11, the demo code from this answer exploits the following implementation:

注意:index_sequence / integer_sequence实用程序从C ++ 14开始提供。由于问题被标记为C ++ 11,因此本答案中的演示代码利用了以下实现:

namespace std
{
    template <std::size_t... Is>
    struct index_sequence {};

    template <std::size_t N, std::size_t... Is>
    struct make_index_sequence_h : make_index_sequence_h<N - 1, N - 1, Is...> {};

    template <std::size_t... Is>
    struct make_index_sequence_h<0, Is...>
    {
        using type = index_sequence<Is...>;
    };

    template <std::size_t N>
    using make_index_sequence = typename make_index_sequence_h<N>::type;
}

#1


7  

template <typename PointT, std::size_t N, std::size_t... Is>
PointT to(std::array<double, N> const& a, std::index_sequence<Is...>)
{
    return PointT(a[Is]...);
}

template <typename PointT, std::size_t N>
PointT to(std::array<double, N> const& a)
{
    return to<PointT>(a, std::make_index_sequence<N>{});
}

DEMO


Note: index_sequence/integer_sequence utilities are available starting from C++14. Since the question is tagged as C++11, the demo code from this answer exploits the following implementation:

注意:index_sequence / integer_sequence实用程序从C ++ 14开始提供。由于问题被标记为C ++ 11,因此本答案中的演示代码利用了以下实现:

namespace std
{
    template <std::size_t... Is>
    struct index_sequence {};

    template <std::size_t N, std::size_t... Is>
    struct make_index_sequence_h : make_index_sequence_h<N - 1, N - 1, Is...> {};

    template <std::size_t... Is>
    struct make_index_sequence_h<0, Is...>
    {
        using type = index_sequence<Is...>;
    };

    template <std::size_t N>
    using make_index_sequence = typename make_index_sequence_h<N>::type;
}