templated overload of opAssign

kdevel kdevel at vogtner.de
Mon Apr 5 15:05:24 UTC 2021


On Sunday, 4 April 2021 at 18:05:04 UTC, tsbockman wrote:
```
[...]
>> You cannot assign void returned from bar() as parameter to 
>> opAssign(). The lazy keyword creates some internal delegate, 
>> thus opAssign() works instead.
[...]
> auto bar (int i) {
>     return () {
>     	if (i == 1)
>             throw new E ("E");
>     };
> }
```

You changed the definition of ``bar`` while the exception 
collector (``EC``) is meant to catch and collect an exception 
thrown from the *unmodified* function. It seems that the operator 
``+=`` or ``~=`` may be better suited to express that intent. 
Rewriting this in terms of ``opOpAssign`` works as expected:

```
import std.stdio;

struct EC {
    Exception [] ex;
    auto opOpAssign (string op: "+", X: void) (lazy X f)
    {
       writeln (__PRETTY_FUNCTION__);
       try return f (); catch (Exception e) ex ~= e;
    }
    auto opOpAssign (string op: "~", X: void) (lazy X f)
    {
       writeln (__PRETTY_FUNCTION__);
       try return f (); catch (Exception e) ex ~= e;
    }
}

class E : Exception { this (string s) { super (s); } }
void bar (int i) { if (i == 1) throw new E ("E"); }

void main ()
{
    EC ec;

    ec.opOpAssign!"+" (bar (1)); // okay
    ec += bar (1); // okay
    ec ~= bar (1); // okay

    ec.writeln;
}
```


More information about the Digitalmars-d-learn mailing list