Automatic counter for derived class / Alternative?

爷,独闯天下 提交于 2019-12-25 08:58:47

问题


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:

  • The Type is not constexpr, but this thing seems not really possible
  • I have the only line of code that need to be put into a source file of my whole library

I 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.


回答1:


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.



来源:https://stackoverflow.com/questions/41006738/automatic-counter-for-derived-class-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!