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?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01