www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion

reply Jiyan <jiyan jiyan.info> writes:
Hello,

I want to convert from ints implicit to a struct type, so for 
example:

struct use
{
	int x;

	int toInt()
	{
		return x;
	}

	use fromInt(int v)
	{
		return use(v);
	}

         alias toInt this; // implicit conversion to int value

	this(int v)
	{x = v;}
}

void useP(int v)
{
	v.writeln;
}

void useV(use v)
{
	v.writeln;
}

void main(string[] args)
{
	use a = use(2);
	//useP(a);
	useV(2); // how can i let this work?
}

Thanks :)
Jan 17 2018
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 01/17/2018 03:15 PM, Jiyan wrote:
 Hello,

 I want to convert from ints implicit to a struct type, so for example:

 struct use
 {
      int x;

      int toInt()
      {
          return x;
      }

      use fromInt(int v)
      {
          return use(v);
      }

          alias toInt this; // implicit conversion to int value

      this(int v)
      {x = v;}
 }

 void useP(int v)
 {
      v.writeln;
 }

 void useV(use v)
 {
      v.writeln;
 }

 void main(string[] args)
 {
      use a = use(2);
      //useP(a);
      useV(2); // how can i let this work?
 }

 Thanks :)
Not possible in D by design. std.conv.to is smart to use the int-taking constructor, which I think is useful in templated code in some cases: import std.conv : to; useV(2.to!use); Ali
Jan 17 2018
prev sibling parent Mike Franklin <slavo5150 yahoo.com> writes:
On Wednesday, 17 January 2018 at 23:15:33 UTC, Jiyan wrote:

 I want to convert from ints implicit to a struct type, so for 
 example:
I'm not sure what your actual use case is, but based on the example, you can just template `useV`. import std.stdio; struct use { int x; int toInt() { return x; } use fromInt(int v) { return use(v); } alias toInt this; // implicit conversion to int value this(int v) {x = v;} } void useP(int v) { v.writeln; } void useV(T)(T v) { v.writeln; } void main(string[] args) { use a = use(2); //useP(a); useV(2); // how can i let this work? } https://run.dlang.io/is/pJhQJh Mike
Jan 17 2018