我不知道为什么这个static_assert()代码不起作用

这是代码:

#pragma once

#include <stdint.h>

namespace Detours
{
    static_assert(sizeof(uintptr_t) == sizeof(void *));
}

我收到此错误消息:

Error (active) E2783 expected a comma (the one-argument version of static_assert is not enabled in this mode)

回答

从 C++17 开始,static_assert声明允许message省略参数。( cppreference )

您需要在编译器中启用 C++17,或者这样完成message参数:

static_assert(sizeof(uintptr_t) == sizeof(void *), "The message you want to show.");

也可以看看

如何在 Visual Studio 中启用 C++17 编译?


回答

static_assert()C++17 标准中引入了(至少由 Microsoft)称为“简洁静态断言”的语言功能 - 即只有一个参数的 。在此之前,第二个参数(一个字符串,错误消息)所需的。因此,使用(例如)MSVC 和“/std:C++14”标志编译您的代码,会出现以下错误:

错误 C2429:语言功能“简洁静态断言”需要编译器标志“/std:c++17”

而 clang-cl 给出:

警告:没有消息的 static_assert 是 C++17 扩展 [-Wc++17-extensions]

要解决此问题,请切换您的编译器以符合 C++17 标准,或者,如果您没有这种可能性,请添加所需的第二个参数:

    static_assert(sizeof(uintptr_t) == sizeof(void*), "Wrong uintptr_t size!");

但请注意,即使如此,也不能保证断言会成功!的uintptr_t类型仅需要具有足够的尺寸容纳正确的指针; 它不具有是完全一样的大小。请参阅:什么是 uintptr_t 数据类型。


以上是我不知道为什么这个static_assert()代码不起作用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>