如何用宏做static_assert? [英] How to do static_assert with macros?

查看:21
本文介绍了如何用宏做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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆