【发布时间】:2015-11-30 21:13:31
【问题描述】:
考虑以下代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
struct BaseClass {
static int identifier() {
static int identifier_counter = 0;
return identifier_counter++;
}
};
template <class D>
struct Class: public BaseClass {
static int identifier() {
static int class_identifier = BaseClass::identifier();
return class_identifier;
}
};
struct A: public Class<A> { };
struct B: public Class<B> { };
int main() {
std::srand(std::time(0));
int r = std::rand()%2;
if(r) {
std::cout << "A: " << A::identifier() << std::endl;
std::cout << "B: " << B::identifier() << std::endl;
} else {
std::cout << "B: " << B::identifier() << std::endl;
std::cout << "A: " << A::identifier() << std::endl;
}
}
这是对问题的简化但仍然合理的表示。
任何派生类在运行时都会有一个特定的、不同的标识符,并且相同类型的两个实例将共享相同的标识符。肯定是解决此类问题的好方法。
不幸的是,这些标识符取决于调用identifier 成员的顺序(我们可以通过多次运行示例来轻松看到)。换句话说,给定两个类A 和B,如果碰巧运行两次软件,它们的identifier 成员以不同的顺序被调用,它们就有不同的标识符。
我的问题是,由于某些原因,我需要将这些标识符存储在某处,并让它们在单次执行中存活下来,这样一旦应用程序再次运行,我就可以对原始类型进行推理,并决定从存储。
另一种方法是使用type_info 中的hash_code,但它会遇到其他问题。另一种解决方案是在应用程序的引导期间强制调用identifier 成员,但这也有几个缺点。
我想知道到目前为止是否有一种易于实现但仍然优雅的解决方案,它对开发人员完全透明,可以识别多次执行的类型,因为上面的解决方案是针对应用程序的单次运行。
【问题讨论】: