一段时间以来,我一直在尝试(断断续续地)想出一个创造性的解决方案来解决这个问题,但到目前为止我还没有做到。我最近认为它可能可以通过模板元编程来解决,尽管由于我相对缺乏该技术的经验,我不确定。
是否可以使用模板元编程(或 C++ 语言的任何其他机制)来计算从某个基类派生的类的数量,以便为每个派生类提供唯一的静态类标识符?
提前致谢!
不。这是一个在实践中经常出现的问题,据我所知,只有两种解决方案:
- 手动为每个派生类分配 ID。
- 动态且延迟地非确定性地生成 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> { ... };
这为您提供了每个类别的唯一 ID:
Derived1::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived3::getStaticId(); // 2
但是,这些 ID 是延迟分配的,因此您调用的顺序getId()
影响ID的返回。
Derived3::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived1::getStaticId(); // 2
这是否适合您的应用程序取决于您的特定需求(例如,不利于序列化)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)