"Value class instance" pattern?
bearophile
bearophileHUGS at lycos.com
Sat Jul 13 09:41:29 PDT 2013
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
More information about the Digitalmars-d
mailing list