How to do static_assert with macros?(如何用宏做static_assert?)
问题描述
我曾尝试使用 此建议 来执行静态断言,但如果我执行此操作,我不会收到编译错误在模板的方法中使用它.
I have tried to use this suggestion to do a static assert, but I do not get a compilation error if I use it within a method of a template.
示例如下:
#include <iostream>
#define STATIC_ASSERT(expr, msg)
{
char STATIC_ASSERTION__##msg[(expr)?1:-1];
(void)STATIC_ASSERTION__##msg[0];
}
template <typename T >
class A
{
public:
int foo(const int k )
{
// does not work
STATIC_ASSERT( k > 9, error_msg );
return k+5;
}
};
int bar(const int k )
{
// works fine
//STATIC_ASSERT( k > 9, error_msg );
return k+5;
}
int main()
{
A<int> a;
const int v = 2;
std::cout<<a.foo(v)<<std::endl;
std::cout<<bar(v)<<std::endl;
// works fine
//STATIC_ASSERT( v > 9, error_msg );
}
我用 g++ 4.7.2 编译它,并警告说 C++ ISO 不支持 VLA:
I compiled it with g++ 4.7.2, with a warning that VLAs are not supported by c++ ISO :
g++ -Wall -g -std=c++98 -Wextra -pedantic gvh.cpp
那么,为什么在模板方法中使用 STATIC_ASSERT 时编译不会失败?有没有办法让它失败?
So, why the compilation doesn't fail when the STATIC_ASSERT is used within the template method? Is there a way to make it fail?
注意:我需要一个 c++98(甚至可能是 c++03)的解决方案,如果可能的话,只能使用宏.
NOTE : I need a c++98 (maybe even c++03) solution, if possible only with macros.
推荐答案
在 C++11 之前我通常会这样做:
Prior to C++11 I would normally do:
typedef int static_assert_something[something ? 1 : -1];
您还可以查看boost static assert.但它太臃肿了,我不喜欢.做大很容易,做更好很难.
You can also look at boost static assert. But it is too bloated for my liking. It is easy to make things bigger, it is hard to make them any better.
这篇关于如何用宏做static_assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用宏做static_assert?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
