【问题标题】:I don't know why this static_assert() code doesn't work我不知道为什么这个 static_assert() 代码不起作用
【发布时间】:2021-03-11 08:20:19
【问题描述】:

这是代码:

#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)

【问题讨论】:

  • 定义“不起作用”。你期望什么结果,你观察到什么结果?
  • Error (active) E2783 expected a comma (the one-argument version of static_assert is not enabled in this mode) 这是我遇到的错误
  • static_assert 在 C++17 之前需要第二个参数 - 错误消息。显然,您的编译器中未启用 C++17。要么弄清楚如何启用它,要么添加错误消息,如static_assert(condition, "Error message here")
  • 您可能还是想添加一条错误消息。
  • 在项目设置中启用c++17。属性 -> C/C++ -> 语言 -> “C++ 语言标准”

标签: c++ static-assert


【解决方案1】:

自 C++17 起,static_assert 声明允许省略 message 参数。 (cppreference)

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

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

另见

How to enable C++17 compiling in Visual Studio?

【讨论】:

    【解决方案2】:

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

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

    而 clang-cl 给出:

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

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

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

    但请注意,即使这样,也不能保证断言会成功! uintptr_t 类型只需要足够大以正确容纳指针;它没有必须是完全相同的大小。请参阅:What is uintptr_t data type

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 1970-01-01
      • 2020-09-19
      • 2014-01-17
      • 1970-01-01
      • 2015-07-06
      • 2013-11-14
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多