25

I'd like to have a C++0x static_assert that tests whether a given struct type is POD (to prevent other programmers from inadvertently breaking it with new members). ie,

struct A // is a POD type
{
   int x,y,z;
}

struct B // is not a POD type (has a nondefault ctor)
{
   int x,y,z; 
   B( int _x, int _y, int _z ) : x(_x), y(_y), z(_z) {}
}

void CompileTimeAsserts()
{
  static_assert( is_pod_type( A ) , "This assert should not fire." );
  static_assert( is_pod_type( B ) , "This assert will fire and scold whoever added a ctor to the POD type." );
}

Is there some kind of is_pod_type() macro or intrinsic that I can use here? I couldn't find one in any C++0x docs, but of course the web's info on 0x is still rather fragmentary.

Community
  • 1
  • 1
Crashworks
  • 40,496
  • 12
  • 101
  • 170
  • 1
    Note that in C++0x, struct B is not POD because it does not have a *trivial default constructor* (see 9.0.10 and 9.0.6 in N3242). I'm not sure what exactly counts as a trivial default constructor (see 12.1.5), but suspect that adding `B() = default;` might turn struct B into a C++0x POD. – Sjoerd Aug 24 '11 at 01:36

1 Answers1

31

C++0x introduces a type traits library in the header <type_traits> for this sort of introspection, and there is an is_pod type trait. I believe that you would use it in conjunction with static_assert as follows:

static_assert(std::is_pod<A>::value, "A must be a POD type.");

I'm using ISO draft N3092 for this, so there's a chance that this is out of date. I'll go look this up in the most recent draft to confirm it.

EDIT: According to the most recent draft (N3242) this is still valid. Looks like this is the way to do it!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 3
    Note that in C++0x, the POD definition has been relaxed and split up. So there is now also `std::is_trivially_copyable<>` and `std::is_standard_layout<>` (see the linked N3242). See http://stackoverflow.com/questions/6496545/trivial-vs-standard-layout-vs-pod/6496703#6496703 for what *trivially copyable* and *standard layout* mean. – Sjoerd Aug 24 '11 at 01:25
  • 1
    Also, `is_pod` was introduced in TR1 for C++03 (or, technically, in [Boost.TypeTraits](http://www.boost.org/libs/type_traits/index.html) before that) -- it's only been made _standard_ in C++0x. – ildjarn Aug 24 '11 at 02:24