hid*_*yat 6 c++ templates sizeof
我有一个模板,它采用具有不同值的结构,例如:
struct Something
{
char str[10];
int value;
...
...
};
Run Code Online (Sandbox Code Playgroud)
在函数内部我使用sizeof运算符:跳入内存 sizeof(Something);
有时我想不跳任何东西; 我希望sizeof返回零.如果我输入一个空结构,它将返回1; 我可以在模板中放置什么来使sizeof返回零?
Ben*_*igt 21
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)
Run Code Online (Sandbox Code Playgroud)
Кон*_*ков 14
你怎么看待这件事?
#include <iostream>
struct ZeroMemory {
int *a[0];
};
int main() {
std::cout << sizeof(ZeroMemory);
}
Run Code Online (Sandbox Code Playgroud)
是的,输出为0.
但是这段代码不是标准的C++.
| 归档时间: |
|
| 查看次数: |
1634 次 |
| 最近记录: |