View mode: basic / threaded / horizontal-split · Log in · Help
September 10, 2005
Implicit casting to/from arrays of one?
It might be useful if all types were implicitly castable to an array of one element.  In 
other words, given a function:

# void foo (int[] x) {}

You could call it with:

# int bar = 123;
# foo(bar);

And it would be as if you had coded:

# int bar = 123;
# int[] tmp;
# tmp ~= bar;
# foo(tmp);

This is distinct from what can currently be done with type-safe variadics, in that it is 
like an implied overload of (T[]) with (T), where the latter only dass pass-thru.

Thoughts?  (This idea just randomly came to be a little bit ago.)

-- Chris Sauls
September 11, 2005
Re: Implicit casting to/from arrays of one?
Chris Sauls wrote:
> It might be useful if all types were implicitly castable to an array of 
> one element.  In other words, given a function:
> 
> # void foo (int[] x) {}
> 
> You could call it with:
> 
> # int bar = 123;
> # foo(bar);
> 
> And it would be as if you had coded:
> 
> # int bar = 123;
> # int[] tmp;
> # tmp ~= bar;
> # foo(tmp);
> 
> This is distinct from what can currently be done with type-safe 
> variadics, in that it is like an implied overload of (T[]) with (T), 
> where the latter only dass pass-thru.
> 
> Thoughts?  (This idea just randomly came to be a little bit ago.)
> 
> -- Chris Sauls

While I agree with the concept, it could cause some problems with 
function overloading.  So the best way forward for this would be to 
require an explicit cast which performs the 'promotion'.

> int bar;
> foo(cast(int[])bar);

While not as convenient, it allows you to have a function of the same 
name that accepts an int as an argument.

I can't see many places that this would be useful, but that's probably 
because former C/C++ devs like myself aren't used to being able to do 
stuff like this.  But I don't see any reason why the D language 
shouldn't be counted on to interpret things like this.

-- 
- EricAnderton at yahoo
September 11, 2005
Re: Implicit casting to/from arrays of one?
pragma wrote:
> Chris Sauls wrote:
> 
>> It might be useful if all types were implicitly castable to an array
>> of one element.  In other words, given a function:
>>
> 
> I can't see many places that this would be useful, but that's probably
> because former C/C++ devs like myself aren't used to being able to do
> stuff like this.
> 

I, on the other hand, often find myself annoyingly reminded that
std.string.atoi() translates only strings, not characters.

Would definitely be a handy addition to the language, cast required or not.
Top | Discussion index | About this forum | D home