www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion by return

reply Hakan Aras <hakan.aras live.at> writes:
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
next sibling parent reply Alex <sascha.orlov gmail.com> writes:
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
parent Hakan Aras <hakan.aras live.at> writes:
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
prev sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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