try & catch / repeating code - DRY
Jacob Carlborg
doob at me.com
Thu May 24 17:39:07 UTC 2018
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.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list