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

时间:2021-02-01 15:29:21

I am using a third party API, which includes a header file that contains a set of typedefs. Over the past 4 years there have been minor changes to some of the typedefs (e.g. switching between unsigned/signed, changing from int to long etc).

我正在使用一个第三方API,它包含一个包含一组typedef的头文件。在过去的4年里,对某些类型的类型(例如:在未签名/签名之间切换,从int到long等)进行了细微的更改。

I want to add a compile time check in my code so that I know if a specific typedef has changed. I was thinking of adding something like the below:

我想在代码中添加一个编译时检查,这样我就可以知道某个特定的类型def是否已经更改。我想添加如下内容:

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

When I tried this out across various typedefs I found that a compile error was always being thrown.

当我在各种类型的typedef中尝试这个时,我发现总是抛出一个编译错误。

I set up a small console program, which showed the same problem (i.e. always false for preprocessor usage) but was fine outside of the preprocessor:

我设置了一个小的控制台程序,它显示了相同的问题(即对于预处理器的使用总是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;
}

I am using Visual Studio 2015.

我正在使用Visual Studio 2015。

How do I implement such a compile time check on expected types (specifically to produce a compile time error if the types are not the same)?

如何实现对预期类型的编译时检查(特别是在类型不相同的情况下产生编译时错误)?

1 个解决方案

#1


5  

The preprocessor doesn't know anything about types. (Hint: It runs before compilation, hence the ‘pre’.)

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

What you want is static_assert. E.g:

你想要的是static_assert。例句:

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

Although, since it's an assertion, perhaps it should say ‘has not’.

虽然,由于它是一个断言,也许它应该说“没有”。

You can put that almost anywhere, even outside of any function.

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

#1


5  

The preprocessor doesn't know anything about types. (Hint: It runs before compilation, hence the ‘pre’.)

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

What you want is static_assert. E.g:

你想要的是static_assert。例句:

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

Although, since it's an assertion, perhaps it should say ‘has not’.

虽然,由于它是一个断言,也许它应该说“没有”。

You can put that almost anywhere, even outside of any function.

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