C++ : how do I use type_traits to determine if a class is trivial?
The definition of POD in C++11 is:
A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).
So unless you are violating the rules of standard layout or something of that nature, is_pod
should be sufficient. And if you're breaking the rules of standard layout, then you can't use memcpy
and memset
and so forth.
So I don't know why you need this unless you trying to test triviality specifically.
For std::memcpy
it is sufficient that the type be trivially copyable. From n3290, 3.9 Types [basic.types] paragraph 2:
For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.
Following paragraphs also describe other useful properties of trivially copyables types (i.e. not just copying to a char
array).
std::is_trivially_copyable
is the trait to detect just that. However as of my writing it's not implemented by e.g. GCC, so you may want to use std::is_trivial
as a fallback (since in turn it requires a trivial copy constructor).
I really do not recommend using is_standard_layout
, unless you really know what you're doing (e.g. language interoperability on one particular platform) it's not what you want. More information on what triviality and standard layout is about to perhaps help you specify the exact requirements you want.