www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion with ctor like C++

reply "Pierre" <cathary.pierre neuf.fr> writes:
Hi everybody,

I would like to use implicit conversion like this:

//Sample class
class MyClass
{
    this(string MyValue){...}
}

//Called function
void MyFunction(Foo MyFoo){}

void main()
{
   MyFunction("Hello World!"); //Failed : MyFunction not 
callable...
}

I saw in forum this is OK because D doesn't do implicit 
conversion with ctor like C++
But how can I do ? May I use alias ?

Thank you for your attention.
Sep 08 2015
next sibling parent "Pierre" <cathary.pierre neuf.fr> writes:
I made a mistake it's more like:

  //Sample class
  class CClass
  {
     this(string MyValue){...}
  }

  //Called function
  void MyFunction(CClass MyClass){}

  void main()
  {
    MyFunction("Hello World!"); //Failed : MyFunction not  
callable...
  }
Sep 08 2015
prev sibling parent reply "Meta" <jared771 gmail.com> writes:
On Tuesday, 8 September 2015 at 19:23:47 UTC, Pierre wrote:
 Hi everybody,

 I would like to use implicit conversion like this:

 //Sample class
 class MyClass
 {
    this(string MyValue){...}
 }

 //Called function
 void MyFunction(Foo MyFoo){}

 void main()
 {
   MyFunction("Hello World!"); //Failed : MyFunction not 
 callable...
 }

 I saw in forum this is OK because D doesn't do implicit 
 conversion with ctor like C++
 But how can I do ? May I use alias ?

 Thank you for your attention.
No, as far as I know, D does not support implicit construction of classes or structs. There is *some* implicit conversion allowed, but in the opposite direction. struct Test { string s; alias s this; //Necessary for nice construction syntax this(string s) { this.s = s; } } void foo(string s) { writeln(s); } void main() { Test t = "asdf"; foo(t); //Prints "asdf" } So with alias this, you can pass a Test to a function expecting a string, but not vice-versa.
Sep 08 2015
parent "Pierre" <cathary.pierre neuf.fr> writes:
OK that's very clear thank you for the answer.
Sep 08 2015