我正在使用第三方API,其中包括一个头文件,该头文件包含一组typedef。在过去的四年中,一些typedef发生了微小的变化(例如,在无符号/有符号之间切换,从int更改为long等)。

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

#if !std::is_same<::ApiType, int>::value
#error Type has changed
#endif

当我尝试各种typedef时,我发现总是抛出编译错误。

我设置了一个小型控制台程序,该程序显示了相同的问题(即对预处理器的使用始终为false),但在预处理器之外还可以:
#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;
}

我正在使用Visual Studio 2015。

如何在期望的类型上实现这种编译时间检查(如果类型不同,则特别是产生编译时间错误)?

最佳答案

预处理器对类型一无所知。 (提示:它在编译之前运行,因此为“pre”。)

您想要的是 static_assert 。例如:

static_assert(std::is_same<::ApiType, int>::value,
              "Type has changed");

尽管由于是断言,也许应该说“没有”。

您可以将它放在几乎任何地方,甚至可以放在任何功能之外。

07-24 09:44
查看更多