digitalmars.D.learn - Implicit conversion by return
- Hakan Aras (14/14) Aug 08 2018 Given this:
- Alex (7/21) Aug 08 2018 I suppose, this is too slack.
- Hakan Aras (3/4) Aug 08 2018 Ah thanks, I was wondering if something like that exists. Still
- Jonathan M Davis (23/37) Aug 08 2018 Num n = 5;
Given this: struct Num { this(int a) {} } Is there any reason why this works: Num n = 5; but this doesnt: Num funk() { return 5; } I understand that I can construct it explicitely, but that gets annoying quickly, especially with templates.
Aug 08 2018
On Wednesday, 8 August 2018 at 08:15:16 UTC, Hakan Aras wrote:Given this: struct Num { this(int a) {} } Is there any reason why this works: Num n = 5; but this doesnt: Num funk() { return 5; } I understand that I can construct it explicitely, but that gets annoying quickly, especially with templates.I suppose, this is too slack. What would work is Num funk() { return typeof(return)(5); }
Aug 08 2018
On Wednesday, 8 August 2018 at 08:44:03 UTC, Alex wrote:return typeof(return)(5);Ah thanks, I was wondering if something like that exists. Still though, that's 16 extra characters that dont need to be there.
Aug 08 2018
On Wednesday, August 8, 2018 2:15:16 AM MDT Hakan Aras via Digitalmars-d- learn wrote:Given this: struct Num { this(int a) {} } Is there any reason why this works: Num n = 5; but this doesnt: Num funk() { return 5; } I understand that I can construct it explicitely, but that gets annoying quickly, especially with templates.Num n = 5; doesn't actually do an implict conversion. It's the same as doing Num n = Num(5); So, I guess that you could call it implicit construction, but regardless, it's just a different syntax for calling the constructor. The only way to create an implicit conversion with a user-defined type in D is to use alias this, and that only provides a way to implicitly convert _from_ a user-defined type, not to a type. So, having Num funk() { return 5; } work is impossible in D, just like having something like auto foo(Num n) { ... } foo(5); work is impossible. If you want to return an int and have it converted to a Num, then you're going to need to explicitly construct a Num from the int. - Jonathan M Davis
Aug 08 2018