派生类的自动计数器/替代方法? [英] Automatic counter for derived class / Alternative?

查看:130
本文介绍了派生类的自动计数器/替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我的库的第一部分有两个最后的问题.第一个是如果没有hack(如果我想要constexpr版本),这在C ++中是不可能的,这是派生的类计数器:

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 {};

必须在源文件中:

int  FooBase::Counter = 0;

为什么我需要这个柜台?好吧,我将其用作一种类型,并将其用作另一个数组的索引.

Why I need this counter? Well I use it as a type and an index into another array.

我对此有两个问题:

  • Type并非constexpr,但是这似乎不太可能
  • 我只有一行代码需要放入整个库的源文件中
  • 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.

即使这意味着添加课程或其他内容,我也希望看到您的建议/替代方法.如果您至少可以删除int FooBase::Counter = 0;行,那就很好了.

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:我没有任何C ++限制,欢迎使用TS.

PS: I don't have any C++ limitations, TS are welcome.

PSS:实际情况要复杂一些,使用CRTP,希望不会有问题.

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.

因此,简而言之,您看到的不是C ++语言的特定缺点,而是单独编译模型的基本限制.这意味着,如果要执行此操作,则需要编写一个在完整的源代码上运行的外部工具,以生成constexpr变量的初始化表达式.

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.

这篇关于派生类的自动计数器/替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆