How to get the number of members in a class at compile time

Viewed 306

I often encounter situations where I have to implement custom copy/move constructors. However some time later, it occurs that the class gets extended with a new member and this custom copy/move constructor is not updated, so I'm searching for a way to prevent the code from compiling without updating these methods.

Header code:

class MyClass
   {
   public:
       MyClass(const MyClass &rhs);
       // ...
   private:
       std::string                 _s;
       std::unique_ptr<OtherClass> _owned;
       bool                        _b;
   };

Cpp code:

MyClass::MyClass(const MyClass &rhs)
    : _s(rhs._s)
    , _b(rhs._b)
    {
    if (rhs._owned)
       _owned = rhs._owned->clone();
    }

So, if I add some member to MyClass, example: std::size_t _size; than I would like a compilation error for the copy constructor.

My current solution is to add:

static_assert(sizeof(MyClass) == 32, "...");

near this implementation of the copy constructor. All of this works fine, unfortunately this only works when the size of the class increases. So if I instead add bool _b2; all compiles unfortunately.

So instead of checking the size, I would like to check the number of members. Unfortunately I haven't found this yet. Are there any suggestions?

I've already considered:

  • banning bool in favor of short, though it breaks all sense of intention.
  • replacing bool by bitset, however different values can't have different names
  • Put all default copyable members in separate struct, which introduces complexity
  • Add static const auto with number of members to the class, hoping this gets updated on adding a member

All these ideas however need code/guideline changes, so ideally I would just like to write static_assert(number_of_members<MyClass>::value == 3, "...");, any ideas?

2 Answers
Related