Template unique IDs per type

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 11 21:42:12 PDT 2013


On Friday, July 12, 2013 05:15:43 Roderick Gibson wrote:
> I was recently looking up how to assign a unique ID based on each
> different implementation of a templated type (NOT per instance,
> but per unique type). For example:
> 
> class MyTemplate(T) {
>       //the ? where the actual number would go
>       const int type_id = ?;
> }
> 
> void main() {
>       auto a = new MyTemplate!(int)(); //a.type_id = 0
>       auto b = new MyTemplate!(string)(); //b.type = 1
>       auto c = new MyTemplate!(int)(); //c.type_id = 0
>       auto d = new MyTemplate!(double)();//d.type_id = 2
> }
> 
> There's some solutions to this sort of thing at this
> stackoverflow question in c++ which are possible at run-time:
> 
> http://stackoverflow.com/questions/8596490/counting-with-template-metaprogra
> mming
> 
> BUT I was wondering with CTFE and/or mixins would it be possible
> to do this at compile time?

You can't have any kind of global mutable state in CTFE, so there's no way for 
different template instantiations to share data like that. You could generate 
IDs based on the types (e.g. a hash) and get different values that way (though 
it might be tricky to do that in a way that would guarantee no collisions), 
but if you want some kind of incrementing ID across them, I think that you're 
stuck with a runtime solution.

Now, it's probably possible to use static constructors to use global mutable 
state to intialize all of those IDs when the program starts up, which would 
initialize the IDs to incrementing values, so they could be immutable if you 
wanted, but that would still be at runtime.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list