Mathieu Van Nevel Mathieu Van Nevel - 8 days ago 6
C++ Question

Constexpr and know how count class

I'm working on an Entity Component System and trying to make the Component type number based on how many class are derived from the Component class itself.

But I think there is some missing features in C++ for doing all I want.
Because the number of Component class should be some constexpr integer that I should use to delimit vector, bitmask etc...
For now I can just have every derived class have an unique type number, but can't detect the size of the bitset which is the number of derived class.

Base:

//!
//! \class ComponentBase
//! \brief Exist only to manage CounterType in a prepocessor way
//!
class ComponentBase {


protected:
static uint32_t CounterType; // Counter of actual component number

public:
virtual ~ComponentBase() {}
};
}

typedef std::bitset<ComponentBase::CounterType> T_Mask;


Derived:

//!
//! \class Component
//! \brief Superclass for Component, stock Type number and Manager
//!
template < typename Derived >
class Component : public ComponentBase {

public:
static const uint32_t Type;

protected:
Component() = default;
};
}

template < typename Derived >
const uint32_t Component<Derived>::Type = ++ComponentBase::CounterType;


But right now I can't use CounterType to set the bitset size.
Tried with a constexpr but without any success.

If you have some ideas, I'm all ears.
Thanks anyways

Ps: I don't have any C++ limitation (G++ 6-2 right now)

Answer

What you are asking for is not possible in c++.

Assume your Base and Derived are available (transitively #included in) via header.hpp and are legal c++

You have the following files in your project:

1.cpp

#include "header.hpp"
class One {};

class ComponentOne : public Component<One> {};

2.cpp

#include "header.hpp"
class Two {};

class ComponentOne : public Component<Two> {};

You spin up cc.exe once to compile 1.cpp into 1.o, and another instance to compile 2.cpp into 2.o, what happens?

Comments