如何使用std :: is_same生成编译时错误?

Cla*_*ton 1 c++ std visual-c++ c-preprocessor

我使用的是第三方API,其中包含一个包含一组typedef的头文件.在过去的4年中,对某些typedef进行了微小的更改(例如,在unsigned/signed之间切换,从int更改为long等).

我想在我的代码中添加编译时检查,以便我知道特定的typedef是否已更改.我想添加如下内容:

#if !std::is_same<::ApiType, int>::value
#error Type has changed
#endif
Run Code Online (Sandbox Code Playgroud)

当我在各种typedef中尝试这个时,我发现总是抛出编译错误.

我设置了一个小的控制台程序,它显示了同样的问题(即对于预处理器使用总是假的)但在预处理器之外很好:

#include "stdafx.h"
#include <Windows.h>
#include <type_traits>

int main()
{
#if std::is_same<int, int>::value
  const auto aa = 14; // omitted
#else
  const auto bb = 17;
#endif

#if std::is_same<::DWORD, int>::value
  const auto cc = 14; // omitted
#else
  const auto dd = 17;
#endif

  const auto a = std::is_same<int, int>::value; // true
  const auto b = std::is_same<::DWORD, int>::value; // false
  const auto c = std::is_same<::DWORD, unsigned long>::value; // true

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2015.

如何对预期类型执行这样的编译时检查(特别是如果类型不相同则产生编译时错误)?

Bif*_*fen 5

预处理器对类型一无所知.(提示:它编译之前运行,因此'pre'.)

你想要的是什么static_assert.例如:

static_assert(std::is_same<::ApiType, int>::value,
              "Type has changed");
Run Code Online (Sandbox Code Playgroud)

虽然,因为它是一个断言,也许它应该说' 没有 '.

你可以把它放在几乎任何地方,甚至在任何功能之外.

  • 我通常手工制作一个清晰易懂的信息,或许有一些关于如何解决任何问题的好方法,但对每个人都有.;) (2认同)