Function templates do implicit conversions for their arguments
Maxim Fomin
maxim at maxim-fomin.ru
Thu Jul 4 11:06:59 PDT 2013
On Thursday, 4 July 2013 at 15:59:21 UTC, TommiT wrote:
> On Thursday, 4 July 2013 at 15:03:54 UTC, Maxim Fomin wrote:
>> [..]
>> 2) In case of one parameter, a variable isn't tied to any type
>> and usual implicit conversions are applied.
>
> Do you mean that if D had the C++ style implicit conversion
> operator (using let's say the keyword '@implicit'), then the
> following would compile?
>
> struct Wrap(T)
> {
> T t;
> }
>
> struct Toy
> {
> alias Wrapped = Wrap!Toy;
>
> @implicit Wrapped opCast(T : Wrapped)()
> {
> return Wrapped.init;
> }
> }
>
> void foo(T)(Wrap!T) { }
>
> void main()
> {
> foo(Toy.init);
> }
>
Your implicit syntax is redundant. What C++ does is irrelevant. D
has alias this.
import std.stdio;
struct Wrap(T)
{
T t;
}
struct Toy
{
alias get this;
Wrap!Toy get()
{
return Wrap!Toy.init;
}
}
void foo(T)(Wrap!T t)
{
writeln(T.stringof);
}
void main()
{
foo(Toy.init);
}
Note, that T is Toy, so there were no type conversion during
template instantiation. There was argument conversion after
instantiation, as it happens usually. Back to foo function
accepting slice - dmd does the same thing.
> On Thursday, 4 July 2013 at 15:03:54 UTC, Maxim Fomin wrote:
>> On Thursday, 4 July 2013 at 13:55:17 UTC, TommiT wrote:
>>> On Thursday, 4 July 2013 at 13:45:07 UTC, Maxim Fomin wrote:
>>>> Actually if you pass integer static array, dmd deduces T to
>>>> be int, [..]
>>>
>>> And that right there, "dmd deduces T to be int", is the crux
>>> of the matter. How on earth is DMD able to deduce T to be
>>> int, without using the implicit conversion from int[10] to
>>> int[] ?
>>
>> DMD is stupid, but not that. If it has T[] parameter, and
>> int[10] static array which is convertible to int[] is passed,
>> T is deduced to be int. What other types T can be? A float,
>> object, or pointer to union?
>
> So you admit that DMD does implicit conversion during type
> deduction?
See above. What type implicit converision did dmd in case of
int[10] and int[]. Conversion from int to int?
> On Thursday, 4 July 2013 at 15:03:54 UTC, Maxim Fomin wrote:
>> On Thursday, 4 July 2013 at 13:55:17 UTC, TommiT wrote:
>>> DMD does the implicit conversion int[10] -> int[] while it is
>>> doing type deduction, which according to TDPL shouldn't
>>> happen.
>>
>> This is flawed since you can:
>>
>> int[10] arr;
>> foo!int(arr).
>
> What exactly in what I said there is flawed? Your example
> foo!int(arr) has nothing to do with what I said, because
> there's no type deduction in your example.
>
Example shows that implicit conversion on argument in this case
has nothing with type deduction (there is no type deduction, yet
argument was converted).
More information about the Digitalmars-d
mailing list