www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Why does it not compile?

reply Morlan <home valentimex.com> writes:
import std.stdio;

void Foo(T:T*)(T arg) if(!is(T==int)) {
  writeln("arg of Foo:", arg, typeid(T));
}
void Foo(T:T*)(T arg) if(is(T==int)) {
  writeln("int Foo!");
}

void main() {
  Foo!(long*)(54);
}
Mar 24 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Morlan:

 ...

This compiles, 54 is an int: import std.stdio; void Foo(T: T*)(T arg) if(!is(T == int)) { writeln("Arg of Foo: ", arg, " ", typeid(T)); } void Foo(T: T*)(T arg) if(is(T == int)) { writeln("int Foo!"); } void main() { Foo!(long*)(54L); } Generally for questions like this, there is the D.learn newsgroup. Bye, bearophile
Mar 24 2011
parent reply Morlan <home valentimex.com> writes:
I did not ask what to do to compile it. I knew that 54L would do. The problem is
that in the example I explicitely specify the template parameter as long* so
there
is no reason for the compiler to try and guess T from the type of the function
argument. There is something wrong here.
Mar 24 2011
next sibling parent reply Daniel Gibson <metalcaedes gmail.com> writes:
Am 24.03.2011 11:49, schrieb Morlan:
 I did not ask what to do to compile it. I knew that 54L would do. The problem
is
 that in the example I explicitely specify the template parameter as long* so
there
 is no reason for the compiler to try and guess T from the type of the function
 argument. There is something wrong here.

I agree. void fun(long l) {} void main() { long foo = 54; fun(42); } works, so that should work without an explicit cast as well. Cheers, - Daniel
Mar 24 2011
parent Morlan <home valentimex.com> writes:
The program below compiles. Clearly the "if" constraints in my original example
are causing trouble. It seems like a bug to me.

import std.stdio;

void Foo(T:T*)(T arg) {
  writeln("arg of Foo:", arg, typeid(T));
}
void main() {
  Foo!(long*)(54);
}
Mar 24 2011
prev sibling parent bearophile <bearophileHUGS lycos.com> writes:
Morlan:

 I did not ask what to do to compile it. I knew that 54L would do. The problem
is
 that in the example I explicitely specify the template parameter as long* so
there
 is no reason for the compiler to try and guess T from the type of the function
 argument. There is something wrong here.

The compiler is not guessing the type here. It's just that the type the template is explicitly instantiated with, and the type T of the data, aren't the same. You see it better with this simpler example: import std.stdio; void foo(T)(T x) if(is(T == int)) { writeln("1"); } void foo(T)(T x) if(!is(T == int)) { writeln("2"); } void main() { foo(1); // 1 foo(1L); // 2 foo!(int)(1); // 1 foo!(long)(1L); // 2 foo!(long)(1); // error foo!(int)(1L); // error } Bye, bearophile
Mar 24 2011