hasDataMember and mixin inconsistency

Philippe Sigaud philippe.sigaud at gmail.com
Sun Jan 27 01:49:23 PST 2013


Hi,

If think in your code, your testing whether or a not a mixin("...")
statement is valid D. Which it is.

I'd put the mixin externally:

template hasDataMember( T, string M )
{
   mixin("
   enum hasDataMember = __traits(
      compiles,
      ( ref T x, ref T y ){ x." ~ M ~ " = y." ~ M ~ "; }
   );");
}

Also, I suppose the Test inner struct is not visible from the
hasDataMember template. The template is instantiated where it's
declared, not where it's called. You could use a mixin template, I
guess.

I'd use a string mixin, but then I was converted to string mixins a
few years ago :)

string hasDataMember( T )(string M )
{
    return " __traits(compiles, {
        Test t;
        auto _ = t.D; // reading t.M
        t." ~ M ~ " = t." ~ M ~ "; // assign to t.M
    })";
}

using is a bit more noisy than your solution: mixin(hadDataMember!(Test)("M"))


> And it works pretty well, but it gets the wrong result for the following
> test case which is commented out. Originally, I thought maybe you were
> allowed to write to the .init member of structures, but writing the same
> code directly without relying on a mixin actually yields the right result
> (all the asserts pass)

You cannot write to .init, it's not a member. It's a built-in
property, like .sizeof or .offsetof.


> 2) Is there a better way to check for the existence of a data member ?

If by data member, you mean some symbol that can be read and written
to, then I'd test just that. See the string mixin before: it tests for
existence, reading and writing.


More information about the Digitalmars-d-learn mailing list