September 21, 2013 Re: Eliminating code duplication for static/nonstatic functions | ||||
---|---|---|---|---|
| ||||
Posted in reply to Simen Kjaeraas | On 9/20/13 8:52 AM, Simen Kjaeraas wrote:
>> I see no way to extract the scaffolding into a library.
>
> Like this?
>
>
> import std.stdio;
>
> mixin template maybeStatic(bool isStatic, alias funDef, args...) {
> static if (isStatic) {
> static mixin funDef!args;
> } else {
> mixin funDef!args;
> }
> }
>
> struct A
> {
> enum hasState = false;
> private mixin template funDef()
> {
> void fun(int x) { writeln(x); }
> }
> mixin maybeStatic!(!hasState, funDef);
> }
>
> void main()
> {
> A a;
> a.fun(42);
> }
>
This is nice. Works with shared, too.
Andrei
|
September 21, 2013 Re: Eliminating code duplication for static/nonstatic functions | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrei Alexandrescu | On Friday, 20 September 2013 at 15:20:36 UTC, Andrei Alexandrescu wrote:
> On 9/19/13 1:02 PM, Andrej Mitrovic wrote:
>> On 9/19/13, Andrei Alexandrescu <SeeWebsiteForEmail@erdani.org> wrote:
>>> I'm not sure I understand how that would work.
>>
>> -----
>> module test;
> [snip]
>
> Thanks, that's the simplest and most effective. I reduced it to:
>
> struct A
> {
> enum hasState = false;
> private mixin template funDef()
> {
> void fun(int x) { writeln(x); }
> }
> static if (hasState)
> mixin funDef!();
> else
> static mixin funDef!();
> }
>
> void main()
> {
> A a;
> a.fun(42);
> }
>
> I see no way to extract the scaffolding into a library.
>
>
> Andrei
You'll be very disapointed when some of your overloads will disapear.
|
September 21, 2013 Re: Eliminating code duplication for static/nonstatic functions | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrei Alexandrescu | On Thursday, 19 September 2013 at 17:10:43 UTC, Andrei Alexandrescu wrote:
> Consider a struct that may or may not have state depending on a type parameter:
I would like to note that this problem is a specific case of the general problem of changing a function's signature based on a compile-time value. The same problem exists with other attributes, and varying the presence of a template or function parameter. One example was that I wanted to define an overload set of function templates, where in some overloads, some parameters were function parameters, and in other overloads, the same parameters were template parameters (there was a significant optimization opportunity when the parameters were known at compile-time).
|
Copyright © 1999-2021 by the D Language Foundation