Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 18, 2013 Unique IDs for each template instantiation at compile-time? | ||||
---|---|---|---|---|
| ||||
I was wondering if it was possible to generate unique(in order) IDs for each template instantiation of a class at compile-time. A short example of what I'm trying to do: static int counter = 0; class A(T) { enum id = counter++; } class B : A!B { } Ofcourse, this doesn't compile because the "counter" variable can't be read at compile-time. |
December 18, 2013 Re: Unique IDs for each template instantiation at compile-time? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Weasel | Weasel:
> I was wondering if it was possible to generate unique(in order) IDs for each template instantiation of a class at compile-time.
I think you can't do this. (It's usually named gensym).
Bye,
bearophile
|
December 19, 2013 Re: Unique IDs for each template instantiation at compile-time? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Weasel | On Thu, Dec 19, 2013 at 12:01:03AM +0100, Weasel wrote: > I was wondering if it was possible to generate unique(in order) IDs for each template instantiation of a class at compile-time. [...] You could use the built-in .mangleof property to get the mangled name of the template, which can then be used as a unique string for that particular template instantiation. The disadvantage is that this is a string, which may be inefficient depending on what you want to do with it. So you may want to take advantage of CTFE by using the hash of this string instead, say using the hashOf function, and use the resulting hash value as your ID. Assuming that the hash function isn't so horrible that two template instantiations' hash values will collide, this ID should be unique. T -- Famous last words: I *think* this will work... |
December 19, 2013 Re: Unique IDs for each template instantiation at compile-time? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Weasel | Am Thu, 19 Dec 2013 00:01:03 +0100 schrieb "Weasel" <weaselcat@gmail.com>: > I was wondering if it was possible to generate unique(in order) IDs for each template instantiation of a class at compile-time. > > A short example of what I'm trying to do: > > static int counter = 0; > class A(T) > { > enum id = counter++; > } > class B : A!B > { > } > > Ofcourse, this doesn't compile because the "counter" variable can't be read at compile-time. Something like that cannot work. Imagine your template is in a.d and you instantiate it in b.d and c.d. Now you compile: dmd -c b.d dmd -c c.d Both times the counter imported from a.d would start at 0. -- Marco |
Copyright © 1999-2021 by the D Language Foundation