Let this() figure out T implicitly?

Ali Çehreli acehreli at yahoo.com
Fri Feb 17 18:22:34 PST 2012


On 02/17/2012 05:59 PM, Timon Gehr wrote:
 > On 02/18/2012 12:04 AM, Ali Çehreli wrote:
 >> On 02/17/2012 09:08 AM, Steven Schveighoffer wrote:
 >>
 >> > What you are asking for is IFTI (Implicit Function Template
 >> > Instantiation) on constructors, and is perfectly possible, but not
 >> > implemented:
 >> >
 >> > http://d.puremagic.com/issues/show_bug.cgi?id=6082
 >>
 >> What was the resolution for the case when the constructor is a template?
 >> I think that's why IFTI doesn't work for structs and classes in C++.
 >> Although, I can't get the following to compile in D anyway (that old and
 >> annoying error message again! :p):
 >>
 >> Error: no property 'opCall' for type 'deneme.B'
 >>
 >> import std.conv;
 >>
 >> class B
 >> {
 >> string s;
 >>
 >> this(T)(T t) // <-- Is the struct a template
 >> // or the constructor a template?
 >
 > The constructor it is, and B is a class, not a struct.

Ah! Thanks!

So today the following works; and not B, but the constructor is a template:

import std.conv;

struct B
{
     string s;

     this(T)(T t)       // <-- constructor is a template
     {
         s = to!string(t);
     }
}

void main()
{
     auto b0 = B(42);       // construct with int
     assert(b0.s == "42");

     auto b1 = B(1.5);      // construct with double
     assert(b1.s == "1.5");
}

With the proposed feature, the struct would be a template.

 >> {
 >> s = to!string(t);
 >> }
 >> }
 >>
 >> void main()
 >> {
 >> auto b0 = B(42);
 >> }
 >>
 >> I wasn't around when the static opCall() was designed but it is probably
 >> the very first thing that bugged me about D. :) I want B(42) to be
 >> object construction, not opCall(), which is not even defined.
 >>
 >> Ali
 >>
 >
 > Why? What useful semantics would that have for classes?

I am not sure but the point is, if function templates provide IFTI, then 
because of being functions the constructors could provide IFTI as well, 
as it does for the struct B above.

As an aside, I don't know why it is not the same with classes. I hope I 
am not again making an error in the following code. I have replaced 
'struct' with 'class' and inserted two 'new' keywords:

import std.conv;

class B
{
     string s;

     this(T)(T t)
     {
         s = to!string(t);
     }
}

void main()
{
     auto b0 = new B(42);   // line 61459
     assert(b0.s == "42");

     auto b1 = new B(1.5);  // line 61462
     assert(b1.s == "1.5");
}

The compiler says:

deneme.d(61459): Error: no constructor for B
deneme.d(61462): Error: no constructor for B
deneme.d(61462): Warning: statement is not reachable

Ali



More information about the Digitalmars-d-learn mailing list