www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - C++ to D: __COUNTER__ & #define alternatives

reply Dominic Jones <dominic.jones gmx.co.uk> writes:
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);".

Any suggestions would be appreciated.

(This question is related to 
https://forum.dlang.org/thread/gqzlchurxylkvwiirrxb forum.dlang.org)


template<std::size_t ID, typename T>
struct Unique { T value; };

// Would prefer something like "__CPU_CLOCK_TICKS__"
// instead of __COUNTER__, if it were available
#define UQ(v) Unique<__COUNTER__, decltype(v)>{v}

int main()
{
   auto c0 = UQ(3);
   auto c1 = UQ(4);
   static_assert(!std::is_same<decltype(c0), decltype(c1)>::value);
}

(at: https://godbolt.org/z/O7lt5f)
Nov 30 2018
parent Stanislav Blinov <stanislav.blinov gmail.com> writes:
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))); }
Nov 30 2018