Eliminating code duplication for static/nonstatic functions

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Sep 19 13:02:31 PDT 2013


On 9/19/13, Andrei Alexandrescu <SeeWebsiteForEmail at erdani.org> wrote:
> I'm not sure I understand how that would work.

-----
module test;

import std.traits;

struct S(T)
{
    enum hasState = FieldTypeTuple!T.length || isNested!T;

    static if (hasState)
        T _theT;
    else
        alias _theT = T;

    private mixin template OpDispatch()
    {
        auto opDispatch(string meth, Args...)(Args args)
        {
            static if (meth == "method")  // specialization ?
                return 1 + _theT.method();
            else
                return mixin("_theT." ~ meth)(args);
        }
    }

    static if (hasState)
        mixin OpDispatch!();
    else
        static mixin OpDispatch!();
}

struct A
{
    static int method() { return 0; }
}

struct B
{
    int i;
    int method() { return i; }
}

void main()
{
    auto a = S!A();
    auto b = S!B(B(1));

    assert(a.method == 1);  // 1 + A.method() == 1
    assert(b.method == 2);  // 1 + b.i == 2
    assert(S!A.method == 1);  // works due to static dispatch
    // assert(S!B.method == 2);  // denied at CT (requires 'this')
}
-----


More information about the Digitalmars-d mailing list