Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wanted to define a variadic tuple type to represent coordinates. For example, for some magic type:

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

I'd like to have CoordT<3>::coord_type to be the 3-dimensional coordinate type:

std::tuple<double, double, double>

.

But I don't know how to use template programming to generate N repeated doubles.

Can anyone please help explain how to write it?

like image 668
thor Avatar asked Jan 09 '19 00:01

thor


People also ask

How do you make a tuple set in C++?

get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. 2. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.

What is a std :: tuple?

Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair. If std::is_trivially_destructible<Ti>::value is true for every Ti in Types , the destructor of tuple is trivial.

Is there tuple in C++?

Tuples in C++A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.

Are tuples immutable C++?

Tuples are immutable. Lists are mutable. Tuples can contain different data types. Lists consist of a singular data type.


2 Answers

Use std::make_integer_sequence to generate a pack of the appropriate length, then map the elements to doubles:

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

like image 132
Brian Bi Avatar answered Oct 20 '22 01:10

Brian Bi


If you don't literally need a std::tuple, but just need something which acts like a tuple, use std::array:

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

std::array has overloads for std::get<I>, std::tuple_size, and std::tuple_element. Most library and language facilities which accept a tuple-like element will support std::array, such as std::apply and structured bindings.

like image 34
Justin Avatar answered Oct 20 '22 01:10

Justin