Am 13.07.2013 18:41, schrieb bearophile:
Benjamin Thaut:

I also wanted to mention the "ListAvailableCtors" template which is a
nice addition in case there is no constructor available to be called
with the given arguments. It will generate a list of all aviable ctors
with the types of its arguments, and thus greatly improve the error
message given when no appropriate constructor can be found:

string ListAvailableCtors(T)()
{
  string result = "";
  foreach(t; __traits(getOverloads, T, "__ctor"))
    result ~= typeof(t).stringof ~ "\n";
  return result;
}

In my original code it was used during construction like this:

static if(is(typeof(result.__ctor(args))))
{
  result.__ctor(args);
}
else
{
  static assert(args.length == 0 && !is(typeof(T.__ctor)), "Don't know
  how to initialize an object of type " ~ T.stringof ~ " with
  arguments:\n" ~ ARGS.stringof ~ "\nAvailable ctors:\n" ~
  ListAvailableCtors!T() );
}

In my version of your code I have just added a template constraint, this
is simpler, and it generates an error at the calling point:

     this(Targs...)(Targs args)
     if (__traits(compiles, _instance.__ctor(args))) {
         classInstanceBuf[] = typeid(T).init[];
         _instance.__ctor(args);
     }

Isn't this enough?

Bye,
bearophile

The problem with your version is that you will get something like:

Can't call ComposedClass.this with arguments (int, int, float)

With my version you will get:

Can't initialize object of type 'Foo' with arguments (int, int, float) available ctors:
(int, int, int)
(int)
(float)

With my version you will instantly know what ctors are available and you don't have to go look it up in the sourcecode.

Kind Regards
Benjamin Thaut

Reply via email to