我有一个模板,它采用具有不同值的结构,例如:
struct Something
{
char str[10];
int value;
...
...
};
在函数内部我使用了 sizeof 运算符:跳入内存 sizeof(Something);
有时我不想跳任何东西;我希望 sizeof 返回零。如果我放入一个空结构,它将返回 1;我可以在模板中放入什么以使 sizeof 返回零?
最佳答案
sizeof
永远不会为零。 (原因:sizeof(T)
是T[]
类型数组中元素之间的距离,要求元素地址唯一)。
也许您可以使用模板来进行 sizeof 替换,它通常使用 sizeof
但专门针对一种特定类型给出零。
例如
template <typename T>
struct jumpoffset_helper
{
enum { value = sizeof (T) };
};
template <>
struct jumpoffset_helper<Empty>
{
enum { value = 0 };
};
#define jumpoffset(T) (jumpoffset_helper<T>::value)
关于c++ - 什么是 sizeof(something) == 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4993650/