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

C++ 如何使用std::is_same生成编译时错误?,c++,visual-c++,std,c-preprocessor,C++,Visual C++,Std,C Preprocessor,我使用的是第三方API,它包含一个包含一组typedef的头文件。在过去的4年中,一些typedef发生了微小的变化(例如,在无符号/有符号之间切换,从int变为long等) 我想在代码中添加一个编译时检查,以便知道特定的typedef是否已更改。我正在考虑添加如下内容: #if !std::is_same<::ApiType, int>::value #error Type has changed #endif #如果!std::值是否相同 #错误类型已更改 #恩迪夫 当我在各

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

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

#if !std::is_same<::ApiType, int>::value
#error Type has changed
#endif
#如果!std::值是否相同
#错误类型已更改
#恩迪夫
当我在各种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;
}
#包括“stdafx.h”
#包括
#包括
int main()
{
#如果std::是相同的::值
const auto aa=14;//省略
#否则
常数自动bb=17;
#恩迪夫
#如果std::是相同的::值
const auto cc=14;//省略
#否则
常数自动dd=17;
#恩迪夫
const auto a=std::is_same::value;//true
const auto b=std::is_same::value;//false
const auto c=std::is_same::value;//true
返回0;
}
我正在使用Visual Studio 2015


我如何在预期类型上实现这种编译时检查(特别是在类型不相同时产生编译时错误)?

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

你想要的是。例如:

static_assert(std::is_same::value,
“类型已更改”);
虽然,因为这是一个断言,也许它应该说“没有”


你可以把它放在任何地方,甚至任何函数之外。

虽然现在不是这样,但你应该把预处理器和编译器看作是两个独立的实体,几乎是两个在源代码上分别运行的不同程序。预处理器首先在源代码上运行,并创建编译器看到并处理的源代码。因此,预处理器对实际C++语言一无所知,包括像标准库的一部分的实体。我通常是“代码>”定义STATICO-AsHealt(e)StistaSyrAtter(E,ye e)//“需要”< /COD>。对于C++17,只有一个参数
static\u assert
。但我认为更具可读性的信息足以让我继续使用宏。我通常会手工制作一个清晰易懂的信息,也许会有一些关于如何解决任何问题的好建议,但每个人都有自己的建议
static_assert(std::is_same<::ApiType, int>::value,
              "Type has changed");