Function Overloading
Gaurav Negi
gauravbackliner at gmail.com
Fri Nov 3 15:26:59 UTC 2023
On Tuesday, 31 October 2023 at 20:09:44 UTC, Salih Dincer wrote:
> ```d
> struct Calculate
> {
> int memory;
> string result;
>
> auto toString() => result;
>
> this(string str)
> {
> add(str);
> }
>
> this(int num)
> {
> add(num);
> }
>
> import std.string : format;
>
> void add(string str)
> {
> result ~= str.format!"%s + ";
> }
>
> void add(int num)
> {
> memory += num;
> add(num.format!"%s");
> }
> }
>
> import std.stdio;
> void main()
> {
> // without constructor:
> Calculate c;
> c.add("x");
> c.add(2);
> c.writeln; // x + 2 +
>
> // with constructor:
> c = Calculate("x");
> c.add(2);
> c.writeln; // x + 2 +
> }
> ```
>
> There is a simple struct like the one above that is not related
> to reality. There can be more than 2 function overloading in
> it, but in our example there are only 2. Without implementing a
> similar function again for each constructor; is it possible to
> do something like `alias add = this;`?
>
> ```d
> struct Calculate
> {
> int memory;
> string result;
>
> auto toString() => result;
>
> // alias add = this;
>
> import std.string : format;
>
> this(string str)
> {
> result ~= str.format!"%s + ";
> }
>
> this(int num)
> {
> memory += num;
> add(num.format!"%s");
> }
> }
> ```
>
> SDB at 79
Can you modify your code with the below code I hope you can get
what you are looking for.
struct Calculate
{
int memory;
string result;
auto toString() => result;
private void addCommon(string str)
{
result ~= str.format!"%s + ";
}
import std.string : format;
this(string str)
{
addCommon(str);
}
this(int num)
{
memory += num;
addCommon(num.format!"%s");
}
}
Thanks
More information about the Digitalmars-d-learn
mailing list