Asking types about their traits (D 1.0)
Burton Radons
burton-radons at shaw.ca
Sun Feb 10 19:10:20 PST 2008
Jarrett Billingsley Wrote:
> "Burton Radons" <burton-radons at shaw.ca> wrote in message
> news:foo388$qsh$1 at digitalmars.com...
>
> >
> > But I'd like it if the presence of a method didn't require a superfluous
> > alias, but could be detected automatically with something like "is (T.pow
> > : T delegate (T))". Any ideas?
> >
> > Maybe I shouldn't be fighting this - the presence of a method even with
> > the correct signature doesn't necessarily imply that it supports the
> > functionality we're requesting. On the other hand, the likelihood of
> > incorrect code being generated seems extremely minute versus the expense
> > of the alias. What do you think?
>
> struct A
> {
>
> }
>
> struct B
> {
> B pow(B other)
> {
> return B();
> }
> }
>
> template HasPow(T)
> {
> const HasPow = is(typeof(&T.pow) == T function(T));
> }
>
> pragma(msg, HasPow!(A) ? "true" : "false"); // prints false
> pragma(msg, HasPow!(B) ? "true" : "false"); // prints true
>
> You were pretty close!
Ah, I thought "nah, it'll just tell me to go to hell since it's invalid code" so I didn't try that.
That seems the incorrect type though; it should be "T function (T, inout T)", which works correctly. The only problem with that is that variadic functions would be "T function (..., inout T)", which actually makes sense to the ABI (that implementations must conform to), so why not allow it, at least for types? It would definitely be an easier solution than any C++-style member-function nonsense.
More information about the Digitalmars-d-learn
mailing list