C ++ 0x元组存储元素向后 [英] C++0x Tuples Store Elements Backwards

查看:177
本文介绍了C ++ 0x元组存储元素向后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一番调查,我发现C ++ 0x将元素以元组向后存储在内存中。

After a bit of investigation, I found that C++0x stores the elements in a tuple backwards in memory.

例如,取这个代码:

std::tuple<char, char, char> x('\0', 'b 'a');
char* y = (char*)&x;
std::cout << sizeof(x) << std::endl;
std::cout << y << std::endl;

当使用GCC 4.5.2编译时,我得到以下输出:

When compiled with the GCC 4.5.2, I get the following output:

3
ab

这最初让我很困惑。为什么数据存储向后?在通过GNU的无意的混淆标题寻找之后,我注意到实现类似于这样:

This initially puzzled me. Why is the data stored backwards? After hunting through GNU's unintentionally obfuscated headers, I noticed that the implementation was similar to this:

template<typename head, typename... tail> class tuple<head, tail...> : public tuple<tail...>
{
  head value;
  ...
};

因为基类包含最后一个元素,所以下一个派生类包含第二个,等等,模板参数的实际顺序是相反的。

Because the base class contains the last element, then the next derived class contains the second to last, etc., the actual order of the template arguments is reversed.

当我第一次进入元组时,我认为我可以使用它们的函数 glInterleavedArrays(),它将顶点数据的数组设置为颜色,纹理坐标,法线和点的元组。当然,如果我创建一个元组的数组,这些数据必须反向输入,如果你忘记把参数放在正确的顺序,这可能会导致真的奇怪的错误。

When I first got into tuples, I thought that I could use them for a function like glInterleavedArrays(), which sets an array of vertex data as tuples of colors, texture coordinates, normals, and points. Of course, if I make an array of tuples, this data will have to be inputted in reverse, which can result in really weird bugs if you happen to forget to put the arguments in the right order.

那么呢?

template<typename... head, typename tail> class tuple<head..., tail> : public tuple<head...>
{
  tail value;
  ...
};

在GCC 4.5.2下:

Under the GCC 4.5.2:

error: parameter pack argument ‘head ...’ must be at the end of the template argument list

未来,我几乎坚持找到另一种方式来实现这一点。还有别的办法吗?

Unless this becomes available in the future, I'm pretty much stuck on finding another way to implement this. Is there another way? Some way to trick the GCC into getting a properly-ordered tuple memory-wise?

推荐答案

你正在探索的元组布局是元组的未指定实现细节。其他实现将具有其他布局。如果你写这个,根据gcc的布局,你的代码可能不能移植到其他std :: libs。

The tuple layout that you are exploring is an unspecified implementation detail of tuple. Other implementations will have other layouts. If you write to this one, depending on gcc's layout, your code may not be portable to other std::libs.

libc ++ 元组实现(例如)具有相反的(有序)布局。

The libc++ tuple implementation (for example) has the opposite (in-order) layout.

这篇关于C ++ 0x元组存储元素向后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆