Right now I have two last problem with the first part of my library. And the first one is this thing not possible in C++ without hack (if I want the constexpr version), it's a derived class counter:
class FooBase {
protected:
static int Counter;
};
class Foo : public FooBase {
public:
static const int Type;
};
const int Foo::Type = ++FooBase::Counter;
struct FooTest : public Foo {};
Must be in a source file:
int FooBase::Counter = 0;
Why I need this counter? Well I use it as a type and an index into another array.
I have two problem with that:
Type
is not constexpr
, but this thing seems not really possibleI can know how many derived class there is (with a macro that's not horrible) if it's can help, but I don't have any idea about something better.
Even if it's means add class or whatever, I'd like to see your suggestions/alternatives. If you can at least remove the int FooBase::Counter = 0;
line, it will be nice.
PS: I don't have any C++ limitations, TS are welcome.
PSS: The real case is a little more complex and use CRTP, I hope it won't be a problem.
It is not possible in principle to have a derived class counter to be a compile time constant. The reason is that the compiler cannot know, when compiling one translation unit, how many derived classes are in other translation units, or in which order you will link them.
Even worse, you might decide to put some object files containing derived classes into a dynamic library that you load at runtime. In that case, the total number of derived classes may change during the run time of the program. And again, there is no way for the compiler to determine if that is the case.
So in short, what you are seeing is not a specific shortcoming of the C++ language, but a fundamental restriction of the separate compilation model. Which means, if you want to do it, you need to write an external tool operating on the complete source code for generating the initializer expressions of the constexpr
variables.