std::tuple 参数中的类型顺序有什么影响吗?

2022-01-20 00:00:00 tuples c++ c++11

假设我想在 tuple 中存储三种类型:intfloatstd::vector<double>

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;

和这个有什么不同

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

由于将 tuple 实现为可变参数基类,我希望生成的类有一个不同的布局,但 在有什么办法?在将类型放入 tuple 时(例如,将最大的放在首位等)时,是否还有任何优化注意事项需要考虑?

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) ?

推荐答案

标准对类型的实际布局没有任何限制.顺序影响的唯一因素是 std::getstd::tuple_element 等的结果.

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.

我知道 libstdc++ 和 Visual C++ 以与给定顺序相反的顺序排列类型;libc++ 按给定的顺序排列类型.这实质上意味着没有可移植的方式来选择始终产生最佳布局的订单.

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.

不过,其他订单也是可能的.允许实现使用总是产生最小尺寸的布局实现元组,但是仍然为 std::get<N> 等保留相同的语义.不过,我不知道有任何标准库实现可以做到这一点.

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.

相关文章