簡體   English   中英

在C ++ 17中定義可變坐標(元組)類型?

[英]defining a variadic coordinate (tuple) type in C++17?

我想定義一個可變元組的類型來表示坐標。 例如,對於某些魔術類型:

template <unsigned int N>
struct CoordT {
  typedef std::tuple<_some_magic_> coord_type;
};

我想讓CoordT<3>::coord_type成為三維坐標類型:

std::tuple<double, double, double>

但我不知道如何使用模板編程來生成N重復的double s。

任何人都可以幫忙解釋如何寫它?

使用std::make_integer_sequence生成一個適當長度的包,然后將元素映射到雙精度:

template <size_t n>
struct TupleOfDoubles {
    template <size_t... i>
    static auto foo(std::index_sequence<i...>) {
        return std::make_tuple(double(i)...);
    }
    using type = decltype(foo(std::make_index_sequence<n>{}));
};

http://coliru.stacked-crooked.com/a/7950876813128c55

如果你不需要std::tuple ,但只需要像元組一樣的東西,使用std::array

template <unsigned int N>
struct CoordT {
  typedef std::array<double, N> coord_type;
};

std::array具有std::get<I>std::tuple_sizestd::tuple_element 接受類似元組的元素的大多數庫和語言工具都將支持std::array ,例如std::apply結構化綁定

玩得太晚了?

如果您可以接受聲明(不需要定義)可變參數模板函數,如下所示

template <std::size_t ... Is>
constexpr auto toIndexSeq (std::index_sequence<Is...> a)
   -> decltype(a);

並且coord_type是在CoordT專業化中定義的,您可以按如下方式編寫它

template <std::size_t N,
          typename = decltype(toIndexSeq(std::make_index_sequence<N>{}))>
struct CoordT;

template <std::size_t N, std::size_t ... Is>
struct CoordT<N, std::index_sequence<Is...>>
 { using coord_type = std::tuple<decltype((void)Is, 0.0)...>; };

以下是完整的C ++ 14編譯示例

#include <tuple> 
#include <type_traits> 

template <std::size_t ... Is>
constexpr auto toIndexSeq (std::index_sequence<Is...> a)
   -> decltype(a);

template <std::size_t N,
          typename = decltype(toIndexSeq(std::make_index_sequence<N>{}))>
struct CoordT;

template <std::size_t N, std::size_t ... Is>
struct CoordT<N, std::index_sequence<Is...>>
 { using coord_type = std::tuple<decltype((void)Is, 0.0)...>; };


int main()
 {
   using t0 = std::tuple<double, double, double, double>;
   using t1 = typename CoordT<4u>::coord_type;

   static_assert( std::is_same<t0, t1>::value, "!" );
 }

一個非常簡潔的方法是使用std::tuple_catstd::array

template <unsigned int N>
struct CoordT {
  using coord_type = decltype(std::tuple_cat(std::array<double, N>{}));
};

允許 std::tuple_cat 支持類似於元組的類型,例如std::array ,但不能保證。 但是,我檢查的每個實現都支持這一點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM