Skip to content

Instantly share code, notes, and snippets.

@pbackus
Last active November 14, 2023 14:12
Show Gist options
  • Save pbackus/2fde8eb2a6eba15905daba65256f33aa to your computer and use it in GitHub Desktop.
Save pbackus/2fde8eb2a6eba15905daba65256f33aa to your computer and use it in GitHub Desktop.
Gensym for D
// Mixin to generate a new identifier that won't repeat within a scope
enum gensym(string prefix = "_gensym") =
`"` ~ prefix ~ `" ~ __traits(identifier, {})["__lambda".length .. $]`;
// Works multiple times on the same line
unittest
{
enum sym1 = mixin(gensym!()); enum sym2 = mixin(gensym!());
static assert(sym1 != sym2);
mixin("int ", sym1, " = 123, ", sym2, " = 456;");
assert(mixin(sym1) == 123);
assert(mixin(sym2) == 456);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment