Boost logo

Boost :

From: John Maddock (John_Maddock_at_[hidden])
Date: 2000-07-23 06:39:33


Beman,

Last time this was discussed, the best candidate that Steve and I came up
with was something like the form given below, usage is very simple, and
since it only generates a typedef, it can be used anywhere (class, function
or namespace scope) without generating any code or data:

namespace boost{

template <bool> struct compile_time_assert;

template <> struct compile_time_assert<true>{};

template<int> struct ct_assert_test{};

}

#define BOOST_CT_ASSERT( B ) typedef
::boost::ct_assert_test<sizeof(::boost::compile_time_assert< ( B ) >)>
BOOST_JOIN(_boost_postulate_details_,__LINE__)

#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y)
#define BOOST_DO_JOIN2(X, Y) X ## Y
#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y )

// test cases, these should all compile, uncomment those tests that are
currently commented out to see error messages:

// Namespace scope
BOOST_CT_ASSERT(sizeof(int) == 4);
BOOST_CT_ASSERT(sizeof(char) == 1);
//BOOST_CT_ASSERT(sizeof(int) == sizeof(char)); // will not compile

// Function (block) scope
void f()
{
  BOOST_CT_ASSERT(sizeof(int) == 4);
  BOOST_CT_ASSERT(sizeof(char) == 1);
  //BOOST_CT_ASSERT(sizeof(int) == sizeof(char)); // should not compile
}

struct Bob
{
  private: // can be in private, to avoid namespace pollution
    BOOST_CT_ASSERT(sizeof(int) == 4);
    BOOST_CT_ASSERT(sizeof(char) == 1);
    //BOOST_CT_ASSERT(sizeof(int) == sizeof(char)); // will not compile
  public:

  // Member function scope: provides access to member variables
  int x;
  char c;
  int f()
  {
#ifndef _MSC_VER // broken sizeof in VC6
    BOOST_CT_ASSERT(sizeof(x) == 4);
    BOOST_CT_ASSERT(sizeof(c) == 1);
#endif
    //BOOST_CT_ASSERT((sizeof(x) == sizeof(c))); // should not compile
    return x;
  }
};

- John.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk