Boost logo

Boost :

From: John Torjo (john.lists_at_[hidden])
Date: 2003-06-19 12:19:55

Hi all,

I was just thinking (actually, I needed this, while doing some coding), that
STATIC_ASSERT could get a little of the SMART_ASSERT flavour.

What am I talking about?
In case a STATIC_ASSERT fails, how about dumping some data that was involved
in the expression?
Before you'll say it's already happening, I found myself wanting more.

Consider the following trivial example:

#include <boost/static_assert.hpp>
#include <string>

template< class type1, class type2>
struct type1_bigger {
    type1_bigger() {
        BOOST_STATIC_ASSERT( sizeof(type1) > sizeof(type2) );

class Test { std::string s; };
int main(int argc, char* argv[])
    // assertion failed
    type1_bigger< int, Test> i;
 return 0;

Gcc3.2 says:
main.cpp: In constructor `type1_bigger<type1, type2>::type1_bigger() [with
   type1 = int, type2 = Test]':
main.cpp:15: instantiated from here
main.cpp:7: `sizeof' applied to incomplete type `

VC6 says:
: error C2027: use of undefined type 'STATIC_ASSERTION_FAILURE<0>'
...\static_assert_ext.cpp(11) : while compiling class-template member
function '__thiscall type1_bigger<int,class Test>::type1_bigger<int,class

and Comeau says:
"ComeauTest.c", line 24: error: incomplete type is not allowed
            instantiation of "type1_bigger<type1, type2>::type1_bigger()
                      type1=int, type2=Test]" at line 73

Now that's not much use for me, since I would like to know sizeof(Test), for

So, we can help the compiler in this direction:
- let the compiler know what to output in case the assertion fails: types or
values. Of course, types are usually outputted anyway, but still, just in
case, depending on your tested expression you might need different types (to
be outputted) as well.

How to do this? Simple ;-)

I've attached an example.
You can also get it from

Compile with your favorite compiler, and see the generated compile-time
errors (I have tested with VC6, gcc3.2 and comeau, but we can modify the
code to work with a lot more compilers).

What do you think?

John Torjo
-- "Practical C++" column writer for
Freelancer, C++ consultant

Boost list run by bdawes at, gregod at, cpdaniel at, john at