Thread overview
equivalent of C++ implicit constructors and conversion operators
Apr 23, 2010
#ponce
Apr 23, 2010
Robert Clipsham
Apr 23, 2010
Philippe Sigaud
April 23, 2010
In C++ implicit constructors and conversion operators allow a user-defined type to act quite like a builtin-type.

  struct half
  {
      half(float x);l
      inline operator float() const;
  }

allows to write:

  half x = 1.f;
  float f = x;

and this is especially useful for templates. I couldn't find a similar construct in D, is there any?
April 23, 2010
On 23/04/10 17:22, #ponce wrote:
> In C++ implicit constructors and conversion operators allow a user-defined type to act quite like a builtin-type.
>
>    struct half
>    {
>        half(float x);l
>        inline operator float() const;
>    }
>
> allows to write:
>
>    half x = 1.f;
>    float f = x;
>
> and this is especially useful for templates.
> I couldn't find a similar construct in D, is there any?

A combination of alias this and opAssign should work:
----
struct half
{
  float f;
  alias f this;
  half opAssign(float fl)
  {
    f = fl;
    return this;
  }
}

void main()
{
  half x;
  // For some reason I got a compilation error with half x = 1f;
  x = 1f;
  float f = x;
}
----
April 23, 2010
On Fri, Apr 23, 2010 at 18:46, Robert Clipsham <robert@octarineparrot.com>wrote:

> On 23/04/10 17:22, #ponce wrote:
>
>> In C++ implicit constructors and conversion operators allow a user-defined type to act quite like a builtin-type.
>>
>>   struct half
>>   {
>>       half(float x);l
>>       inline operator float() const;
>>   }
>>
>> allows to write:
>>
>>   half x = 1.f;
>>   float f = x;
>>
>> and this is especially useful for templates.
>> I couldn't find a similar construct in D, is there any?
>>
>
> A combination of alias this and opAssign should work:
> ----
> struct half
> {
>  float f;
>  alias f this;
>  half opAssign(float fl)
>  {
>    f = fl;
>    return this;
>  }
> }
>
> void main()
> {
>  half x;
>  // For some reason I got a compilation error with half x = 1f;
>  x = 1f;
>  float f = x;
> }
>

Could the compilation error comes from the compiler rewriting half f = 1f;
into half f(1f); or somesuch and trying to call a constructor?
I'm tearing my hair due to errors/confusions between constructors and opCall
for structs.

Anyway, in your example, adding

this(float f) { this.f = f;}

is enough to get half f = 1f; to compile.