C++ to D: __COUNTER__ & #define alternatives

Stanislav Blinov stanislav.blinov at gmail.com
Fri Nov 30 16:14:25 UTC 2018


On Friday, 30 November 2018 at 15:27:07 UTC, Dominic Jones wrote:
> Hello,
>
> I would like to transliterate the following code, below, to D, 
> but it seems to be more difficult than I expected.
>
> I cannot find a keyword, like __COUNTER__, that would enable 
> the construction of unique types each time UQ is used. Even if 
> such a keyword did exist, I cannot find a way wrap it such that 
> I can have statements like "auto c0 = UQ(3);".

You can use __FILE__ and __LINE__. The only limitation there is, 
obviously, one declaration per line.

struct Unique(T, string file, size_t line) {
     T value;
}

auto UQ(T, string file = __FILE__, size_t line = __LINE__)(auto 
ref T value) {
     return Unique!(T, file, line)(value);
}

void main() {
     auto c0 = UQ(3);
     auto c1 = UQ(4);
     static assert(!is(typeof(c0) == typeof(c1)));
}



More information about the Digitalmars-d mailing list