使用模板元编程计数? [英] Counting With Template Metaprogramming?
问题描述
我一直试图想出一个创造性的解决方案(开启和关闭)一段时间,但我还没有能够。我最近认为它可能是模板元编程可以解决的,虽然我不确定,因为我相对缺乏该技术的经验。
I've been trying to think up a creative solution to this problem (on and off) for some time, but I have not as of yet been able to. I recently considered that it might be solvable with template metaprogramming, though I am not sure due to my relative lack of experience with the technique.
是否可以使用模板元编程(或使用C ++语言的任何其他机制)来计算从某个基类派生的类的数量,以便为每个派生类赋予唯一的静态类标识符?
Is it possible to use template metaprogramming (or any other mechanism with the C++ language) to count the number of classes which are derived from some base class such that each derived class is given a unique, static class identifier?
提前致谢!
推荐答案
没有。这是一个在实践中出现的问题,据我所知,只有两个解决方案:
No. This is a problem that comes up in practice quite a lot, and as far as I'm aware there are only two solutions:
- 手动为每个派生类分配ID。
- 动态且懒惰地生成ID。但
你做第二个的方式是这样的:
The way you do the second one is something like this:
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:
This gives you unique IDs for each class:
Derived1::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived3::getStaticId(); // 2
但是,这些ID是懒惰分配的,所以您调用的订单 getId()
会影响返回的ID。
However, those IDs are assigned lazily, so the order you call getId()
affects the ID's returned.
Derived3::getStaticId(); // 0
Derived2::getStaticId(); // 1
Derived1::getStaticId(); // 2
您的应用程序是否合适取决于您的特定需求(例如,没有序列化的好处。)
Whether or not this is OK for your application depends on your particular needs (e.g. would be no good for serialisation).
这篇关于使用模板元编程计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!