Reputation: 3073
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).
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:
#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.
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:
#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.
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)?
Upvotes: 2
Views: 1347
Reputation: 6355
The preprocessor doesn't know anything about types. (Hint: It runs before compilation, hence the ‘pre’.)
What you want is static_assert
. E.g:
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.
Upvotes: 6