c++ - template-based compile time assert with custom messages can only be compiled in some of the compilers -


this code demos compile time assert using template. found can compiled g++ (4.4.7) following cmd line.

$ g++ -std=c++98 a.cpp -o 

nether icc (13.0.1) nor visual c++ (14.00.50727.762 80x86) can compile it. icc, generate error msg this

$ icpc a.cpp -o a.cpp(13): error: non-integral operation not allowed in nontype template argument       compile_time_assert(true && "err msg");       ^  a.cpp(13): error: class "compiletimeassert<<error-constant>>" has no member "check"       compile_time_assert(true && "err msg");       ^  compilation aborted a.cpp (code 2) 

however found assertions true && "err msg" used in run-time assert add custom messages in assert?

questions are

  1. can solved without modifying code, proper compile options?
  2. if can't, alternative methods of compile time assert custom messages?

demo code show follows.

#include <iostream>  template<bool b> class compiletimeassert { }; template<> class compiletimeassert<true> {  public:   static inline void check() { } };  #define compile_time_assert(b) compiletimeassert<(b)>::check()  int main() {     compile_time_assert(true && "err msg");     std::cout<<(true && "err msg")<<std::endl;     return 0; } 

answer first question "no". argument pass template called "non-type template argument". according standard, such arguments must be:

constant expressions, addresses of functions or objects external linkage, or addresses of static class members.

an expression true && "err msg" strictly speaking cannot determined @ compile time. that's why can used run-time assertions not in compile-time ones. g++ demonstrates here non-standard behaviour.

as answer second question, propose following pattern:

#define static_assert(e,m) extern char (*__static_assert_failed(void)) [ 1 - 2*!(e) ]  

__static_assert_failed here pointer external function returning array of chars. array has size of 1 - 2*!(e) became negative if e false causing compile-time error.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -