如何用宏做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.
相关文章