Template unique IDs per type
Roderick Gibson
kniteli at gmail.com
Thu Jul 11 21:48:28 PDT 2013
On Friday, 12 July 2013 at 04:42:28 UTC, Jonathan M Davis wrote:
> 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
Hmm, I'll look into the static constructors, as that sounds like
a fairly ideal solution anyway. I was more just curious to see if
the problem was solvable in D at compile time (as it seems to be
a fairly common request in C++).
More information about the Digitalmars-d-learn
mailing list