用模板元编程计数?

Dan*_*atz 9 c++ inheritance templates template-meta-programming

我一直试图想出一个创造性的解决方案来解决这个问题(开启和关闭)一段时间,但我还没有能够做到.我最近认为它可以通过模板元编程来解决,但由于我相对缺乏该技术的经验,我不确定.

是否可以使用模板元编程(或使用C++语言的任何其他机制)来计算从某个基类派生的类的数量,以便为每个派生类提供唯一的静态类标识符?

提前致谢!

Pet*_*der 6

不.这是一个在实践中出现的问题,据我所知,只有两个解决方案:

  1. 手动为每个派生类分配ID.
  2. 动态地和懒惰地非确定性地生成ID.

你做第二个的方式是这样的:

class Base
{
    virtual int getId() const = 0;
};

// Returns 0, 1, 2 etc. on each successive call.
static int makeUniqueId()
{
    static int id = 0;
    return id++;
}

template <typename Derived>
class BaseWithId : public Base
{
    static int getStaticId()
    {
        static int id = makeUniqueId();
        return id;
    }

    int getId() const { return getStaticId(); }
};

class Derived1 : public BaseWithId<Derived1> { ... };
class Derived2 : public BaseWithId<Derived2> { ... };
class Derived3 : public BaseWithId<Derived3> { ... };
Run Code Online (Sandbox Code Playgroud)

这为您提供了每个类的唯一ID:

Derived1::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived3::getStaticId(); // 2
Run Code Online (Sandbox Code Playgroud)

但是,这些ID是懒惰分配的,因此您调用的顺序getId()会影响返回的ID.

Derived3::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived1::getStaticId(); // 2
Run Code Online (Sandbox Code Playgroud)

这对您的应用程序是否合适取决于您的特定需求(例如,对序列化没有好处).