Getting the error from __traits(compiles, ...)

Bill Baxter wbaxter at gmail.com
Thu Nov 12 06:03:43 PST 2009


We can pretty much already use __traits(compiles,{...}) to implement
static interface checking.

template checkInterface(T) {
    enum bool checkInterface =
    __traits(compiles,
    {
       T x;
       // some code exercising various aspects of the interface
    });
}

The main problem with this is that a static "implements interface"
check is done like so:

   static assert(checkInterface!(myType));

And all it tells you is a single yes or no.  It would help in
debugging if you could somehow get the reason for the failure.

So how to do it?  All that comes to mind is something like the evil
Errno from C.  A global that gets set by the last failure.
Let's call it __errmsg, but it could be a pragma, or a __traits thing.
 If you had that then you could write this:

   assertImplements!(checkInterface!(myType));

With:
template assertImplements(bool v)
{
       static if (!v) {
            pragma(msg, __errmsg);
            static assert(false);
       }
}

There are lots of ways you could provide such a concept-checker, but
they all require the basic ability to get the reason for the
__traits(compiles) failure.

Any other thoughts about how to get the failure info?   This is
probably the main complaint against __traits(compiles), that there's
no way to find out what went wrong if the code doesn't compile.  Often
it can just be a typo.  I know I've spent plenty of time looking at
static if(__traits(compiles, ...)) checks that weren't working only to
discover I switched an x for a y somewhere.  Or passed the wrong
number of arguments.

--bb



More information about the Digitalmars-d mailing list