Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ throwing compilation error on sizeof() comparison in preprocessor #if

I have this which does not compile with the error "fatal error C1017: invalid integer constant expression" from visual studio. How would I do this?

template <class B>
A *Create()
{
  #if sizeof(B) > sizeof(A)
  #error sizeof(B) > sizeof(A)!
  #endif
  ...
}
like image 789
Ramónster Avatar asked Nov 11 '09 19:11

Ramónster


2 Answers

The preprocessor does not understand sizeof() (or data types, or identifiers, or templates, or class definitions, and it would need to understand all of those things to implement sizeof).

What you're looking for is a static assertion (enforced by the compiler, which does understand all of these things). I use Boost.StaticAssert for this:

template <class B>
A *Create()
{
  BOOST_STATIC_ASSERT(sizeof(B) <= sizeof(A));
  ...
}
like image 85
Josh Kelley Avatar answered Oct 31 '22 16:10

Josh Kelley


Preprocessor expressions are evaluated before the compiler starts compilation. sizeof() is only evaluated by the compiler.

like image 28
David Joyner Avatar answered Oct 31 '22 17:10

David Joyner