www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - alias this with template class?

reply "Namespace" <rswhite4 googlemail.com> writes:
I think this should work:

[code]
import std.stdio;

class Foo(T) {
public:
	T Num;
	
	 property
	Foo!(U) ConvertTo(U)() inout {
		return cast(Foo!(U)) this;
	}
	
	alias ConvertTo this;
}

void Call(const Foo!(float) FFoo) {

}

void main() {
	Foo!(ubyte) UbFoo = new Foo!(ubyte)();
	
	Call(UbFoo);
	
	readln();
}
[/code]

Why it doesn't?
Jun 03 2012
parent reply Timon Gehr <timon.gehr gmx.ch> writes:
On 06/03/2012 08:43 PM, Namespace wrote:
 I think this should work:

 [code]
 import std.stdio;

 class Foo(T) {
 public:
      T Num;

       property
      Foo!(U) ConvertTo(U)() inout {
          return cast(Foo!(U)) this;
      }

      alias ConvertTo this;
 }

 void Call(const Foo!(float) FFoo) {

 }

 void main() {
      Foo!(ubyte) UbFoo = new Foo!(ubyte)();

      Call(UbFoo);

      readln();
 }
 [/code]

 Why it doesn't?
Making this generally work as you expect would be too hard. The compiler would have to reverse-engineer the 'ConvertTo' template which is an undecidable problem in general. Some clever heuristics might suffice for most practical instances though, but those are very open-ended and therefore it is hard to incorporate them into the language definition. If you think it should be done you could file a suggestion (enhancement request) into the bug tracker.
Jun 03 2012
parent "Namespace" <rswhite4 googlemail.com> writes:
Fail.
Ok, i tried something like this:
[code]
import std.stdio;

mixin template TConvertTo(T : Object,  U) {
	T!(U) ConvertTo() inout {
		return cast(T!U) this;
	}
	
	alias ConvertTo this;
}

class Foo(T) {
public:
	T Num;
	
	mixin TConvertTo!(typeof(this), float);
	
}
[/code]

but it fails with:
template_alias_this_cast.d(4): Error: template instance T!(float) 
T is not a template declaration, it is a class
template_alias_this_cast.d(4): Error: T!(float) is used as a type
template_alias_this_cast.d(15): Error: mixin 
template_alias_this_cast.Foo!(float).Foo.TConvertTo!(Foo,float) 
error instantiating
template_alias_this_cast.d(19): Error: template instance 
template_alias_this_cast.Foo!(float) error instantiating

If i change it to:
[code]
import std.stdio;

mixin template TConvertTo(V) {
	Foo!(V) ConvertTo() inout {
		return cast(Foo!V) this;
	}
	
	alias ConvertTo this;
}

class Foo(T) {
public:
	T Num;
	
	mixin TConvertTo!(float);
	
}
[/code]

it works. But i think my first idea should work, too.
Jun 03 2012