Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

The example follows :

#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 );
}

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

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?

NOTE : I need a c++98 (maybe even c++03) solution, if possible only with macros.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
545 views
Welcome To Ask or Share your Answers For Others

1 Answer

Prior to C++11 I would normally do:

typedef int static_assert_something[something ? 1 : -1];

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...