Class template argument deduction from constructor call

Jonathan M Davis jmdavisProg at gmx.com
Wed Oct 27 16:08:12 PDT 2010


On Wednesday, October 27, 2010 13:26:21 div0 wrote:
> On 27/10/2010 21:02, "Jérôme M. Berger" wrote:
> > div0 wrote:
> >> On 27/10/2010 20:36, sergk wrote:
> >>> class Foo(T) {
> >>> 
> >>>       this(T t) {
> >>>       
> >>>           bar = t;
> >>>       
> >>>       }
> >>>       T bar;
> >>> 
> >>> }
> >>> 
> >>> void main() {
> >>> 
> >>>       auto a = new Foo(123); // doesn't work
> >>>       auto b = new Foo!(int)(123); // work, but redundant
> >>> 
> >>> }
> >>> 
> >>> Is there any technical limitations preventing this, or its just a
> >>> compiler bug?
> >> 
> >> It's not a bug.
> >> 
> >> I guess it could be a short cut, but it can only ever work when the
> >> class has exactly one constructor, which seems a bit of a pointless
> >> short cut and adds an unneccassiry corner case to the language spec.
> >> 
> > 	Why would it only be able to work when there is exactly one
> > 
> > constructor? Doesn't function overloading work with templates?
> > 
> > 	This works here:
> > void foo(T) (T x) {
> > }
> > 
> > void foo(T, U) (T x, U y) {
> > }
> > 
> > void main()
> > {
> > 
> >      foo (3);
> >      foo (3, "azerty");
> > 
> > }
> > 
> > 		Jerome
> 
> class Foo(T) {
>         this(T t) {
>             bar = t;
>         }
> 
> 	this(string x) {
> 	}
> 
> 	this(int x) {
> 	}
> 
>         T bar;
> }
> 
> auto	f0 = new Foo("wtf?");
> auto	f1 = new Foo(42);
> 
> What's T in any of the above?
> 
> There's no obvious answer for the first 2 and anything anybody says will
> be a source of endless arguments and bike shedding.

The obvious answer would be that this shouldn't compile because it's ambiguous. 
If you force the constructors which conflict with the templated constructor to be 
template specializations, then the problem goes away. However, IIRC, 
unfortunately, at the moment, you can't have a function which has a templated 
and non-templated version regardless of the number of parameters, though I 
believe that there is a bug report on it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list