ness" in c++/c++11?
I have some code which takes a packed POD structure/class and copies it into a memory block.
struct A
{
int a;
int b;
} a;
memcpy(mymemoryblock, (void *)&a, sizeof(A));
// later I get a reply and...
memcpy((void *)&a, mymemoryblock, sizeof(A));
This is only valid for POD types of data, and what I would like to know if there is a way I can test for POD-ness. If someone accidentally adds a member function to this class, the memcpy operations become invalid, but still compilable. This leads to very difficult to detect bugs.
Is there a is_POD_type(A) function, or some other trick that can be used to detect PODness at runtime or compile time?
std::is_pod<A>::value
in C++11.
[Edit: refer to Luc's comment above, in C++11 you don't need the type to be POD for what you're doing.
For that matter you also don't need to cast to void*
, and C-style casting pointers to void*
unnecessarily is a tiny bit risky, because some day you'll cast away const
by accident!]
In C++03 there's no standard way to do it, but Boost has its own is_pod
that errs on the side of caution on compilers that don't provide a non-standard way to find out. So it's useful if you're writing code where the POD special case is an optimization (you just won't get the optimization everywhere). It's also useful if you only care about compilers for which Boost can get an accurate answer. It's not so good if false negatives by is_pod
cause your code to give up in disgust.
The standard (C++98) says that only types with C-like construction/destruction semantics can be members of a union. That covers most of the things that would make a type non-POD, so just define a union type with a member of type A and the compiler should complain if A is not POD.
There is exist a method to call std::tr1::is_pod
Also you can use bycicle like:
#define CHECK_TYPE_IS_A_POD(TYPE)
{
switch(1)
{
case 1:
TYPE IF_COMPILE_ERROR_THEN__##TYPE##__IS_NOT_A_POD;
/* prune out any warnings about not usage */
IF_COMPILE_ERROR_THEN__##TYPE##__IS_NOT_A_POD = TYPE();
case 2:
;
}
But it doen't work for namespace qualification names and specialized template types.
链接地址: http://www.djcxy.com/p/40302.html上一篇: 结构与类