Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
June 08, 2014 scope exit in mixin template | ||||
---|---|---|---|---|
| ||||
Can we not use scope(..) in a mixin template? struct bar {} bar* c_make() { return new bar(); } void c_free(bar* b) { b = null; } mixin template Foo() { auto b = c_make; scope(exit) if(b) c_free(b); } void main() { mixin Foo; } I get Error: Declaration expected, not '(' -Byron |
June 08, 2014 Re: scope exit in mixin template | ||||
---|---|---|---|---|
| ||||
Posted in reply to Byron | On Sunday, 8 June 2014 at 18:28:25 UTC, Byron wrote:
>
> Can we not use scope(..) in a mixin template?
>
> struct bar {}
> bar* c_make() { return new bar(); }
> void c_free(bar* b) { b = null; }
>
> mixin template Foo() {
> auto b = c_make;
> scope(exit) if(b) c_free(b);
> }
>
> void main() {
> mixin Foo;
> }
>
> I get Error: Declaration expected, not '('
>
> -Byron
Mixin templates can only insert declarations, not arbitrary code. When it sees "scope", it's expecting it to be the attribute, not the declaration.
|
June 08, 2014 Re: scope exit in mixin template | ||||
---|---|---|---|---|
| ||||
Posted in reply to monarch_dodra | On Sunday, 8 June 2014 at 18:48:03 UTC, monarch_dodra wrote:
> Mixin templates can only insert declarations, not arbitrary code. When it sees "scope", it's expecting it to be the attribute, not the declaration.
To add to that, if you want to mixin arbitrary code, then you can use a string mixin:
template declare_bar(string var_name) {
enum declare_bar =
"auto " ~ var_name ~ " = c_make();" ~
"scope(exit) if(" ~ var_name ~ ") c_free(" ~ var_name ~ ");"
}
void main() {
mixin(declar_var!"b")
}
For example.
That said, given your example, simply using an RAII wrapper *could* be superior (depends on your actual usecase).
|
June 08, 2014 Re: scope exit in mixin template | ||||
---|---|---|---|---|
| ||||
Posted in reply to Byron | On Sunday, 8 June 2014 at 18:28:25 UTC, Byron wrote:
> void c_free(bar* b) { b = null; }
Heads up: This code does nothing. You are passing the pointer by value, so "b = null;" will have no effect at the end of the call. Use pass by ref:
void c_free(ref bar* b) { b = null; }
|
June 08, 2014 Re: scope exit in mixin template | ||||
---|---|---|---|---|
| ||||
Posted in reply to monarch_dodra | On Sun, 08 Jun 2014 19:44:12 +0000, monarch_dodra wrote:
> On Sunday, 8 June 2014 at 18:28:25 UTC, Byron wrote:
>> void c_free(bar* b) { b = null; }
>
> Heads up: This code does nothing. You are passing the pointer by value,
> so "b = null;" will have no effect at the end of the call.
> Use pass by ref:
>
> void c_free(ref bar* b) { b = null; }
yeah it was sample code, this idea was make and free were c library functions
|
Copyright © 1999-2021 by the D Language Foundation