如何使用 std::is_same 产生编译时错误?
How to use std::is_same to generate compile time errors?
我正在使用第三方 API,它包含一个包含一组 typedef 的头文件。在过去的 4 年里,一些 typedef 发生了微小的变化(例如,在 unsigned/signed 之间切换,从 int 变为 long 等)。
我想在我的代码中添加编译时检查,以便我知道特定的 typedef 是否已更改。我正在考虑添加如下内容:
#if !std::is_same<::ApiType, int>::value
#error Type has changed
#endif
当我在各种 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;
}
我正在使用 Visual Studio 2015.
我如何对预期类型实施这样的编译时检查(特别是在类型不相同时产生编译时错误)?
预处理器对类型一无所知。 (提示:它运行 before 编译,因此是‘pre’。)
你要的是static_assert
。例如:
static_assert(std::is_same<::ApiType, int>::value,
"Type has changed");
虽然,既然是断言,或许应该说'has not'。
您几乎可以将它放在任何地方,甚至可以放在任何函数之外。
我正在使用第三方 API,它包含一个包含一组 typedef 的头文件。在过去的 4 年里,一些 typedef 发生了微小的变化(例如,在 unsigned/signed 之间切换,从 int 变为 long 等)。
我想在我的代码中添加编译时检查,以便我知道特定的 typedef 是否已更改。我正在考虑添加如下内容:
#if !std::is_same<::ApiType, int>::value
#error Type has changed
#endif
当我在各种 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;
}
我正在使用 Visual Studio 2015.
我如何对预期类型实施这样的编译时检查(特别是在类型不相同时产生编译时错误)?
预处理器对类型一无所知。 (提示:它运行 before 编译,因此是‘pre’。)
你要的是static_assert
。例如:
static_assert(std::is_same<::ApiType, int>::value,
"Type has changed");
虽然,既然是断言,或许应该说'has not'。
您几乎可以将它放在任何地方,甚至可以放在任何函数之外。