| Thread overview | |||||
|---|---|---|---|---|---|
|
May 19, 2020 Is it possible to implement operators as ordinary functions? | ||||
|---|---|---|---|---|
| ||||
I was wandering if it possible to implement operators as ordinary functions instead of as member functions of a class or struct for example something like this:
```
import std.stdio: writeln;
struct Int{
int data = 0;
}
Int opBinary(string op)(Int x1, Int x2)
{
static if((op == "+") || (op == "-") || (op == "*") || (op == "/"))
{
int ret;
mixin("ret = x1.data " ~ op ~ " x2.data");
return ret;
}else{
static assert(0, "Operator unknown.");
}
}
void main()
{
Int x = Int(1);
Int y = Int(2);
writeln("Output: ", x + y);
}
```
| ||||
May 19, 2020 Re: Is it possible to implement operators as ordinary functions? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to data pulverizer | On Tuesday, 19 May 2020 at 02:36:24 UTC, data pulverizer wrote:
> I was wandering if it possible to implement operators as ordinary functions instead of as member functions of a class or struct for example something like this:
nope, it must be done as member functions.
| |||
May 19, 2020 Re: Is it possible to implement operators as ordinary functions? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Tuesday, 19 May 2020 at 02:42:22 UTC, Adam D. Ruppe wrote:
> On Tuesday, 19 May 2020 at 02:36:24 UTC, data pulverizer wrote:
>> I was wandering if it possible to implement operators as ordinary functions instead of as member functions of a class or struct for example something like this:
>
> nope, it must be done as member functions.
Thanks!
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply