www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Unique IDs for each template instantiation at compile-time?

reply "Weasel" <weaselcat gmail.com> writes:
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.
Dec 18 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
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
Dec 18 2013
prev sibling next sibling parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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...
Dec 18 2013
prev sibling parent Marco Leise <Marco.Leise gmx.de> writes:
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
Dec 19 2013