Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does type order in std::tuple arguments have any effects?

Tags:

c++

c++11

tuples

Say I want to store three types in a tuple : int, float and std::vector<double>

If I leave aside matters of subsequent interface, does this

tuple<int, float, vector<int>> t;

have any differences from this

tuple<vector<int>, int, float> t;

Due to the implementation of tuple as a class of variadic bases, I'm expecting a different layout for the produced classes, but does it matter in any way ? Also are there any optimization considerations to take into account, when placing types in a tuple (eg put the largest first etc) ?

like image 456
Nikos Athanasiou Avatar asked May 28 '14 11:05

Nikos Athanasiou


People also ask

Are tuples ordered C++?

std::tuple is an ordered list of types.

Is std :: tuple a container?

The new std::array and std::tuple containers provide developers with additional ways to manage structured data efficiently.

How is tuple implemented?

std::tuple can be implemented as a recursive tuple. template <typename T, int index> struct Wrapper { T type; }; template <int index, typename T, typename... Tail> struct Tuple : Wrapper<T, index> , Tuple<index + 1, Tail...>

What is std :: tuple?

(since C++11) 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.


2 Answers

The standard doesn't place any restrictions on the actual layout of the types. The only things the order influences are the results of std::get<N>, std::tuple_element<N, T> and so on.

I know that libstdc++ and Visual C++ lay out the types in reverse order of the order given; libc++ lays out the types in the order given. This essentially means that there is no portable way to pick an order that always produces the best layout.

Other orders are possible, though. An implementation is allowed to implement tuple with a layout that always produces minimal size but still preserves the same semantics for std::get<N> and so on. I don't know of any standard library implementation that does this, though.

like image 181
R. Martinho Fernandes Avatar answered Oct 07 '22 01:10

R. Martinho Fernandes


The standard does not specify an implementation for std::tuple. However it guarantees that std::tuple<A,B,C> shall be a different type than for example std::tuple<B,A,C>. std::tuple is an ordered list of types.

boost::fusion provides a data type for a set style container of types, for cases where the order is not important: boost::fusion::set<>

like image 20
Danvil Avatar answered Oct 07 '22 00:10

Danvil