如何在 C 中使用静态断言来检查传递给宏的参数类型 [英] How to use static assert in C to check the types of parameters passed to a macro
问题描述
我需要编写一个 C 宏来检查以确保传递给它的所有参数都是 unsigned
并且是相同的整数类型.例如:所有输入参数为 uint8_t
,或全部为 uint16_t
,或全部为 uint32_t
,或全部为 uint64_t
.
I need to write a C macro that checks to ensure all parameters passed to it are unsigned
and of the same integer type. Ex: all input params are uint8_t
, or all uint16_t
, or all uint32_t
, or all uint64_t
.
以下是如何在 C++ 中完成此类检查:使用 static_assert 检查传递给宏的类型
Here is how this type of checking can be done in C++: Use static_assert to check types passed to macro
C 中是否存在类似的东西,即使只是通过 gcc 扩展?
Does something similar exist in C, even if only by way of a gcc extension?
请注意,静态断言可通过 _Static_assert
在 gcc 中使用.(在此处查看我的答案:C 中的静态断言).
Note that static asserts are available in gcc via _Static_assert
. (See my answer here: Static assert in C).
这不起作用:
int a = 1;
int b = 2;
_Static_assert(__typeof__ a == __typeof__ b, "types don't match");
错误:
main.c: In function ‘main’:
main.c:23:20: error: expected expression before ‘__typeof__’
_Static_assert(__typeof__ a == __typeof__ b, "types don't match");
<小时>
更新:
这正是如何在 C++ 中做我想做的事(使用 函数模板、static_assert
和 <type_traits>
头文件).为了比较的目的,我无论如何都需要学习这个,所以我就这样做了.在此处为自己运行此代码:https://onlinegdb.com/r1k-L3HSL.
#include <stdint.h>
#include <stdio.h>
#include <type_traits> // std::is_same()
// Templates: https://www.tutorialspoint.com/cplusplus/cpp_templates.htm
// Goal: test the inputs to a "C macro" (Templated function in this case in C++) to ensure
// they are 1) all the same type, and 2) an unsigned integer type
// 1. This template forces all input parameters to be of the *exact same type*, even
// though that type isn't fixed to one type! This is because all 4 inputs to test_func()
// are of type `T`.
template <typename T>
void test_func(T a, T b, T c, T d)
{
printf("test_func: a = %u; b = %u; c = %u; d = %u
", a, b, c, d);
// 2. The 2nd half of the check:
// check to see if the type being passed in is uint8_t OR uint16_t OR uint32_t OR uint64_t!
static_assert(std::is_same<decltype(a), uint8_t>::value ||
std::is_same<decltype(a), uint16_t>::value ||
std::is_same<decltype(a), uint32_t>::value ||
std::is_same<decltype(a), uint64_t>::value,
"This code expects the type to be an unsigned integer type
"
"only (uint8_t, uint16_t, uint32_t, or uint64_t).");
// EVEN BETTER, DO THIS FOR THE static_assert INSTEAD!
// IE: USE THE TEMPLATE TYPE `T` DIRECTLY!
static_assert(std::is_same<T, uint8_t>::value ||
std::is_same<T, uint16_t>::value ||
std::is_same<T, uint32_t>::value ||
std::is_same<T, uint64_t>::value,
"This code expects the type to be an unsigned integer type
"
"only (uint8_t, uint16_t, uint32_t, or uint64_t).");
}
int main()
{
printf("Begin
");
// TEST A: This FAILS the static assert since they aren't unsigned
int i1 = 10;
test_func(i1, i1, i1, i1);
// TEST B: This FAILS to find a valid function from the template since
// they aren't all the same type
uint8_t i2 = 11;
uint8_t i3 = 12;
uint32_t i4 = 13;
uint32_t i5 = 14;
test_func(i2, i3, i4, i5);
// TEST C: this works!
uint16_t i6 = 15;
uint16_t i7 = 16;
uint16_t i8 = 17;
uint16_t i9 = 18;
test_func(i6, i7, i8, i9);
return 0;
}
如果 TEST A 未注释,您会在静态断言中遇到此故障,因为输入不是无符号的:
With just TEST A uncommented, you get this failure in the static assert since the inputs aren't unsigned:
main.cpp: In instantiation of ‘void test_func(T, T, T, T) [with T = int]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',46)">main.cpp:46:29</span>: required from here
main.cpp:32:5: error: static assertion failed: This code expects the type to be an unsigned integer type
only (uint8_t, uint16_t, uint32_t, or uint64_t).
static_assert(std::is_same<decltype(a), uint8_t>::value ||
^~~~~~~~~~~~~
如果 TEST B 未注释,您将无法从模板中找到有效函数,因为模板要求所有输入都是相同类型 T
:
with just TEST B uncommented, you get this failure to find a valid function from the template since the template expects all inputs to be the same type T
:
main.cpp: In function ‘int main()’:
main.cpp:54:29: error: no matching function for call to ‘test_func(uint8_t&, uint8_t&, uint32_t&, uint32_t&)’
test_func(i2, i3, i4, i5);
^
main.cpp:26:6: note: candidate: template void test_func(T, T, T, T)
void test_func(T a, T b, T c, T d)
^~~~~~~~~
main.cpp:26:6: note: template argument deduction/substitution failed:
main.cpp:54:29: note: deduced conflicting types for parameter ‘T’ (‘unsigned char’ and ‘unsigned int’)
test_func(i2, i3, i4, i5);
^
只要 TEST C 未注释,它就会通过,看起来像这样!
And with just TEST C uncommented, it passes and looks like this!
Begin
test_func: a = 15; b = 16; c = 17; d = 18
参考资料:
- http://www.cplusplus.com/reference/type_traits/is_same/一个>
- https://en.cppreference.com/w/cpp/types/is_same
- https://en.cppreference.com/w/cpp/language/decltype
- 我该怎么做将模板类限制为某些内置类型?
相关:
- 使用 static_assert 检查传递给的类型宏 [我自己的答案]
- C 中的静态断言 [我自己的答案]
- Use static_assert to check types passed to macro [my own answer]
- Static assert in C [my own answer]
推荐答案
如果这里最重要的方面是你希望它编译失败 if a
and b
是不同的类型,您可以使用 C11 的 _Generic
以及 GCC 的 __typeof__
扩展来管理它.
If the most important aspect here is that you want it to fail to compile if a
and b
are different types, you can make use of C11's _Generic
along with GCC's __typeof__
extension to manage this.
一个通用的例子:
#include <stdio.h>
#define TYPE_ASSERT(X,Y) _Generic ((Y),
__typeof__(X): _Generic ((X),
__typeof__(Y): (void)NULL
)
)
int main(void)
{
int a = 1;
int b = 2;
TYPE_ASSERT(a,b);
printf("a = %d, b = %d
", a, b);
}
现在如果我们尝试编译这段代码,它会编译得很好,每个人都很高兴.
Now if we try to compile this code, it will compile fine and everybody is happy.
如果我们把b
的类型改成unsigned int
,但是编译会失败.
If we change the type of b
to unsigned int
, however, it will fail to compile.
之所以有效,是因为 _Generic
选择使用控制表达式的类型(在本例中为 (Y)
)来选择要遵循的规则并插入与该规则对应的代码.在这种情况下,我们只为 __typeof__(X)
提供了一个规则,因此如果 (X)
不是 (Y)
的兼容类型,没有合适的规则可供选择,因此无法编译.为了处理具有将衰减为指针的控制表达式的数组,我添加了另一个 _Generic
以另一种方式确保它们必须相互兼容,而不是接受单向兼容.而且因为——就我特别关心的——我们只想确保它在不匹配时编译失败,而不是在匹配时执行特定的操作,所以我给了相应的规则不做任何事情的任务:(void)NULL
This works because _Generic
selection uses the type of a controlling expression ((Y)
in this case) to select a rule to follow and insert code corresponding to the rule. In this case, we only provided a rule for __typeof__(X)
, thus if (X)
is not a compatible type for (Y)
, there is no suitable rule to select and therefore cannot compile. To handle arrays, which have a controlling expression that will decay to a pointer, I added another _Generic
that goes the other way ensuring they must both be compatible with one another rather than accepting one-way compatibility. And since--as far as I particularly cared--we only wanted to make sure it would fail to compile on a mismatch, rather than execute something particular upon a match, I gave the corresponding rule the task of doing nothing: (void)NULL
这种技术有一个问题:_Generic
不处理可变可修改类型,因为它是在编译时处理的.因此,如果您尝试使用可变长度数组执行此操作,它将无法编译.
There is a corner case where this technique stumbles: _Generic
does not handle Variably Modifiable types since it is handled at compile time. So if you attempt to do this with a Variable Length Array, it will fail to compile.
要处理固定宽度无符号类型的特定用例,我们可以修改嵌套的 _Generic
来处理它,而不是处理数组的特殊性:
To handle your specific use-case for fixed-width unsigned types, we can modify the nested _Generic
to handle that rather than handling the pecularities of an array:
#define TYPE_ASSERT(X,Y) _Generic ((Y),
__typeof__(X): _Generic ((Y),
uint8_t: (void)NULL,
uint16_t: (void)NULL,
uint32_t: (void)NULL,
uint64_t: (void)NULL
)
)
传递不兼容类型时的示例 GCC 错误:
Example GCC error when passing non-compatible types:
main.c: In function 'main':
main.c:7:34: error: '_Generic' selector of type 'signed char' is not compatible with any association
7 | __typeof__(X): _Generic ((Y),
| ^
值得一提的是,作为 GCC 扩展的 __typeof__
不会成为所有编译器都可移植的解决方案.不过,它似乎确实适用于 Clang,因此这是另一个支持它的主要编译器.
It is worth mentioning that __typeof__
, being a GCC extension, will not be a solution that is portable to all compilers. It does seem to work with Clang, though, so that's another major compiler supporting it.
这篇关于如何在 C 中使用静态断言来检查传递给宏的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!