How can I detect whether a class has an implicit constructor AND primitive members in c++?

284 Views Asked by At

I want to detect during compile time (static assertion) whether a class meets both the following conditions:

  • Has an implicit default constructor (i.e., no user-defined default constructor).
  • Has at least one data member which is a pod (i.e., a member whose default initialization is to assume whatever random bytes was in its memory address). [I hope I used the term pod correctly here]

The idea is to avoid working with objects with uninitialized members. I know there are different methods to do this during coding, but I also want a mechanism to detect this during compilation. I tried using different std/boost functions, such as is_trivially_constructible, is_pod, but none of these provide the exact terms I need.

For example, let's say I have the following classes:

struct A
{
  int a;
}

struct B
{
  int* b;
}

struct C
{
  bool c;
  std::string c_str_; 
}

struct D
{
  D();
  float d; 
}

struct E
{
  std::string e;
}

Assuming the function I need is called "has_primitive_and_implicit_ctor", I would like the output for each call to be as in the comments:

has_primitive_and_implicit_ctor<A>(); //true - A has at least one pod type member (int)
has_primitive_and_implicit_ctor<B>(); //true - A has at least one pod type member (pointer)
has_primitive_and_implicit_ctor<C>(); //true - A has at least one pod type member (bool), even though there is one non-pod member
has_primitive_and_implicit_ctor<D>(); //false - has a pod member(float), but a user defined ctor
has_primitive_and_implicit_ctor<E>(); //false - doesn't have a default ctor but has no pod members
1

There are 1 best solutions below

5
On BEST ANSWER

Firstly, it seems to me like a broken design to expect from the user of a class to care about its member initialisation. You should make sure in the class itself that all its members are initialised, not somewhere else where it is used.

What you are looking for does not exist, and if it would, it would not even help you. The existence of an explicit constructor does not guarantee that a data member is initialised. On the other hand, with C++11 it is even possible to initialise data members without explicitly writing a constructor (using the brace syntax in the class declaration). Also you just seem to care about uninitialised POD members, but what about uninitialised non-POD members?

That said, compiler can generate warnings about uninitialised values, but often you have to enable this warning (e.g. -Wuninitialized option for gcc). Most compilers allow to force treating warnings as an error. In combination this can give you the desired effect even without specifically writing code to test for it, and it would also work for any uninitialised values, not only those in classes. Maybe this is the solution you are looking for.