__traits(compileError, {})

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 7 18:18:46 PDT 2017

Lately, I've been hit by several compilation errors when phobos 
fails to construct an instance of a class or struct I've pass it. 
Regardless of what the exact failure is, phobos usually gives you 
some generic error that isn't helpful.


class Test {
     @disable this();

int main(string[] argv) {
     auto sz = __traits(classInstanceSize, Test);
     auto mem = malloc(sz)[0..sz];
     return 0;

The above code fails with this error:

'Error: static assert  "Don't know how to initialize an object of 
type Test with arguments ()"'

@disable'd constructors are only one of the reasons I've hit this 
Once though, I was having an extremely hard time figuring out 
what was wrong, and the fix was simply to modify emplace(). I 
removed the line below from emplace(), and forced the constructor 
call, which led to a much more helpful error.

`// static if (is(typeof(result.__ctor(args1))))`

If you simply did that though, it may not be obvious to everyone 
what happened, but if you had __traits(compilerError, {}) then 
you could dress the error up as appropriate:

"Emplace failed with error:\n\t'" ~ __traits(compileError, { 
result.__ctor(args1) }) ~ "."

The alternative would be to manually code redundant error checks 
that the compiler already does into everything in phobos that 
needs to construct objects, which seems much worse than 
implementing something like __traits(compileError, {}).


More information about the Digitalmars-d mailing list