try & catch / repeating code - DRY
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Thu May 24 20:19:53 UTC 2018
On Thursday, May 24, 2018 19:39:07 Jacob Carlborg via Digitalmars-d-learn
wrote:
> On 2018-05-24 08:05, Robert M. Münch wrote:
> > Hi, great! Thanks for the examples... BTW: Is there a place where such
> > generic and fundamental examples are collected?
>
> Not as far as I know.
>
> >> void handleException1(alias dg)()
> >> {
> >> try dg();
> >> catch (Exception e) { /* handle exception */ }
> >> }
> >>
> >> void handleException2(lazy void dg)
> >> {
> >> try dg();
> >> catch (Exception e) { /* handle exception */ }
> >> }
> >>
> >> void handleException3(scope void delegate () dg)
> >> {
> >> try dg();
> >> catch (Exception e) { /* handle exception */ }
> >> }
> >>
> >> void main()
> >> {
> >> handleException1!({
> >> writeln("asd");
> >> });
> >>
> >> handleException1!(() => writeln("asd"));
> >>
> >> handleException2(writeln("asd"));
> >>
> >> handleException3({
> >> writeln("asd");
> >> });
> >> }
> >
> > What is exactly the difference between handleException1 and 3?
>
> With handleException1 the delegate needs to be passed as a template
> argument, in the other case as a regular argument. I thought that the
> lambda syntax, () => writeln("asd"), did not work as a regular argument,
> but I checked now and it does.
>
> Passing it as a template argument might allow the compiler to inline it.
> All range functions in Phobos are using template argument approach.
With a template alias, it will accept pretty much any symbol (which would
then normally be restricted by a template constraint so that it's a symbol
which is usable in the target context), whereas an explicit delegate will
only accept anything that implicitly converts to a delegate with that
signature. What matches, I don't know, since I pretty much enver declare
explicit delegates, though I don't find it surprising that a lambda works,
since that's basically what a lambda is. But I expect that if you did
something like pass a functor, it would work with the alias but wouldn't
work with the delegate parameter.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list