什么是sizeof(某事)== 0?

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)

  • @Let_Me_Be - 我认为这不是所建议的,但你可以做出类似*外观和行为*的东西,但对于你关心的案例会返回0. (5认同)
  • @Let_Me_Be:我从来没有说过我要重新定义`sizeof`关键字,而是创建一些可以替代的新东西. (4认同)
  • 你不能重载`sizeof`运算符 (2认同)

Кон*_*ков 14

你怎么看待这件事?

 #include <iostream>
 struct ZeroMemory {
     int *a[0];
 };
 int main() {
     std::cout << sizeof(ZeroMemory);
 }
Run Code Online (Sandbox Code Playgroud)

是的,输出为0.

但是这段代码不是标准的C++.

  • 是的,你让我知道:/sf/ask/3314686441/#47352751 (2认同)