www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How does alias exactly work

reply Ruby The Roobster <michaeleverestc79 gmail.com> writes:
I thought alias could work like this with classes:

alias test = MyClass(3,"H",9.1); //Assume the constructor 
parameters for MyClass are (int,string,double).

Can anybody fix this code?
Sep 28 2020
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 9/28/20 6:46 PM, Ruby The Roobster wrote:
 I thought alias could work like this with classes:
That would work with template parameters: alias A = Foo!(3, "hello");
 
 alias test = MyClass(3,"H",9.1); //Assume the constructor parameters for 
 MyClass are (int,string,double).
 
 Can anybody fix this code?
You have to write a function (or a lambda): class MyClass { this(int, string, double) { } } auto test1() { return new MyClass(3,"H",9.1); } auto test2 = () => new MyClass(4, "I", 10.1); void main() { test1(); test2(); } However, I assumed each invocation would create a new object. If not, something like this: MyClass test3; static this() { test3 = new MyClass(5, "J", 11.1); } test3 is a single instance for each thread. A single instance for the whole program would be a different exercise. :) Ali
Sep 28 2020
prev sibling parent Paul Backus <snarwin gmail.com> writes:
On Tuesday, 29 September 2020 at 01:46:56 UTC, Ruby The Roobster 
wrote:
 I thought alias could work like this with classes:

 alias test = MyClass(3,"H",9.1); //Assume the constructor 
 parameters for MyClass are (int,string,double).

 Can anybody fix this code?
`alias` lets you create a new name for an entity that already exists somewhere in your program. The "entity" in question can be a lot of different things--a type, a variable, a function, a module, a template--but it must be something that exists independently of the alias. In other words, you cannot use `alias` to give a name to something that does not already have one. But wait, you might ask, if that's true, how can you alias a lambda? It's an anonymous function; by definition, it doesn't have a name! alias increment = (int x) => x + 1; The thing is...lambdas actually do have names. They're just generated internally by the compiler. You can't actually *use* them in your code, but they do occasionally show up in error messages: increment("hello"); // Error: function literal `__lambda1(int x)` is not callable using argument types `(string)`
Sep 28 2020