问题
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) ?
回答1:
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.
回答2:
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<>
回答3:
The standard does not specify how a tuple
should be implemented and it is entirely possible that an implementation reorders the arguments to produce a better layout while preserving the semantics of std::get<int N>
. However, I do not know of any implementation that actually does this since arranging a set of types in a order that produces a good layout is difficult.
It is likely that a different order of arguments is going to produce a different layout. If this matters depends on your use-case. If you want to optimize here you should consider size constraints (additional padding) and cache line size of your target architecture.
来源:https://stackoverflow.com/questions/23910161/does-type-order-in-stdtuple-arguments-have-any-effects