peo*_*oro 10 c++ templates types runtime rtti
我有一个类层次结构,如下所示:
class A { } //
class AA : A { } // A
class AAA : AA { } // / \
class AAB : AA { } // AA AB
class AB : A { } // / \ / \
class ABA : AB { } // AAA AAB ABA ABB
class ABB : AB { } //
Run Code Online (Sandbox Code Playgroud)
我想为这个ierarchy模拟RTTI(当然不使用它),在给定指针/引用的情况下A,我可以找到它的实际类型(类似于什么typeid),作为一个标识类.
此外,我希望识别我的类型的整数集合是连续的,从0到N-1(在我的例子中从0到6):
class A { virtual int t(){return 0;} } //
class AA : A { virtual int t(){return 1;} } // A(0)
class AAA : AA { virtual int t(){return 2;} } // / \
class AAB : AA { virtual int t(){return 3;} } // AA(1) AB(4)
class AB : A { virtual int t(){return 4;} } // / \ / \
class ABA : AB { virtual int t(){return 5;} } // AAA(2) AAB(3) ABA(5) ABB(6)
class ABB : AB { virtual int t(){return 6;} } //
Run Code Online (Sandbox Code Playgroud)
(顺序并不重要:例如,A::t可以返回3和AAB::t0.
是否可以让编译器将索引分配给我的类?
我认为CRTP可以帮助我; 就像是:
class X : A, AssignFirstAvailableIndex< X > { }
Run Code Online (Sandbox Code Playgroud)
但我对模板不够好.我怎么能实现该AssignFirstAvailableIndex模板类?
(当然编译器可以在编译时看到所有类)
有一个标准方法可以实现您的需要。标准区域设置方面使用它来标识自己。考虑检查标准标头“区域设置”。
class Base {
public:
// Being constructed contains a new unique identifier
class Id {
// An id factory returns a sequence of nonnegative ints
static int allocate() {
static int total = 0;
return total++;
}
int _local;
public:
Id(): _local(allocate()) {}
int get() const {return _local;}
};
//Child classes should make this function return an id generated by Base::Id constructed as static member.
virtual int id() const = 0;
};
class Child1{
public:
static const Base::Id _id;
virtual int id() { return _id.get(); }
};
class Child2 {
public:
static const Base::Id _id;
virtual int id() { return _id.get(); }
};
class Child3 {
public:
static const Base::Id _id;
virtual int id() { return _id.get(); }
};
Run Code Online (Sandbox Code Playgroud)
静态成员可以在实现文件中初始化,或者被模板化以允许直接从标头实例化,或者被重构以进行延迟初始化。