包含 comptime 断言的整数常量表达式宏
Integer constant expression macros with comptime assertions in them
我的一些C宏,需要扩展到整数常量表达式,基于以下内容进行编译时断言:
#define stc_assert_expr(CexprB) sizeof(struct{int _:(CexprB)?1:-1;})
也可以拼写为
#include <assert.h>
#define stc_assert_expr(CexprB) sizeof(struct{static_assert(CexprB,#CexprB);})
//^not sure if this is legal C but it compiles with gcc and clang
//(I'm using the bitfield version anyway, which is definitely legal C)
愚蠢的示例用法:
#include <assert.h>
#define stc_assert_expr(CexprB) sizeof(struct{int _:(CexprB)?1:-1;})
int main(int argc, char**argv)
{
#define minus1(X) (0*stc_assert_expr((X)>0)+(X)-1)
/*an integer constant expression with an assertionin it*/
char ar[minus1(3)];
switch(argc){
case minus1(2): ;
}
}
假设我想使这些宏也可以在C++中使用。
上面的例子不起作用,因为C++不接受 sizeof
中的结构定义。是否有一种C++结构可以替换我的stc_assert_expr(CexprB)
来保持static_assert语义?
您可以使用数组表达式而不是结构定义 - 负数组大小在两种语言中都是非法的:
#define stc_assert_expr(condition) sizeof(char[(condition) ? 1 : -1])
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 使用自动推导的 lambda 参数作为常量表达式
- 生成提升::hana::set 的常量表达式问题
- 为什么不能用常量表达式声明数组?
- 不是 lambda 函数中的常量表达式
- 函数调用在常量表达式中必须具有常量值
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 关于在需要常量表达式的上下文中使用的glvalue常量表达式的问题
- 生成 constexpr 字符串表,不能产生常量表达式
- 整体模板参数。错误:在常量表达式中使用'this'
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:'new'不能出现在常量表达式中
- 我可以写出小于 -0.5 两个 ulps 的常量表达式双精度吗?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- C++ 使用变量而不是常量表达式初始化数组
- 使用函数参数作为常量表达式的一部分 - gcc vs clang
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"