Template Mixins - D Programming Language
Description: D Programming Language
Keywords: D programming language

Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Forums
  - IRC
  - Community Discord
  - Wiki
  - GitHub
  - Issues
  - Get involved
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# Template Mixins

Contents

1. Mixin Scope

A TemplateMixin takes an arbitrary set of declarations from the body of a TemplateDeclaration and inserts them into the current context.

    TemplateMixinDeclaration:
        mixin template Identifier TemplateParameters Constraintopt { DeclDefsopt }

    TemplateMixin:
        mixin MixinTemplateName TemplateArgumentsopt Identifieropt ;

    MixinTemplateName:
        . MixinQualifiedIdentifier
        MixinQualifiedIdentifier
        Typeof . MixinQualifiedIdentifier

    MixinQualifiedIdentifier:
        Identifier
        Identifier . MixinQualifiedIdentifier
        TemplateInstance . MixinQualifiedIdentifier

A TemplateMixin can occur in declaration lists of modules, classes, structs, unions, and as a statement. The MixinTemplateName refers to a TemplateDeclaration or TemplateMixinDeclaration. If the TemplateDeclaration has no parameters, the mixin form that has no !(TemplateArgumentList) can be used.

Unlike a template instantiation, a template mixin's body is evaluated within the scope where the mixin appears, not where the template declaration is defined. It is analogous to cutting and pasting the body of the template into the location of the mixin into a nested scope. It is useful for injecting parameterized ‘boilerplate’ code, as well as for creating templated nested functions, which is not always possible with template instantiations.

    import std.stdio : writeln;

    mixin template Foo()
    {
        int x = 5;
    }

    mixin Foo;

    struct Bar
    {
        mixin Foo;
    }

    void main()
    {
        writeln("x = ", x);         // prints 5
        {
            Bar b;
            int x = 3;

            writeln("b.x = ", b.x); // prints 5
            writeln("x = ", x);     // prints 3
            {
                mixin Foo;
                writeln("x = ", x); // prints 5
                x = 4;
                writeln("x = ", x); // prints 4
            }
            writeln("x = ", x);     // prints 3
        }
        writeln("x = ", x);         // prints 5
    }

Mixins can be parameterized:

    mixin template Foo(T)
    {
        T x = 5;
    }

    mixin Foo!(int);           // create x of type int

Mixins can add virtual functions to a class:

    import std.stdio : writeln;

    mixin template Foo()
    {
        void func() { writeln("Foo.func()"); }
    }

    class Bar
    {
        mixin Foo;
    }

    class Code : Bar
    {
        override void func() { writeln("Code.func()"); }
    }

    void main()
    {
        Bar b = new Bar();
        b.func();      // calls Foo.func()

        b = new Code();
        b.func();      // calls Code.func()
    }

Mixins are evaluated in the scope of where they appear, not the scope of the template declaration:

    int y = 3;

    mixin template Foo()
    {
        int abc() { return y; }
    }

    void test()
    {
        int y = 8;
        mixin Foo; // local y is picked up, not global y
        assert(abc() == 8);
    }

Mixins can parameterize symbols using alias parameters:

    mixin template Foo(alias b)
    {
        int abc() { return b; }
    }

    void test()
    {
        int y = 8;
        mixin Foo!(y);
        assert(abc() == 8);
    }

This example uses a mixin to implement a generic Duff's device for an arbitrary statement (in this case, the arbitrary statement is in bold). A nested function is generated as well as a delegate literal, these can be inlined by the compiler:

    import std.stdio : writeln;

    mixin template duffs_device(alias low, alias high, alias fun)
    {
        void duff_loop()
        {
            if (low < high)
            {
                auto n = (high - low + 7) / 8;
                switch ((high - low) % 8)
                {
                    case 0: do { fun(); goto case;
                    case 7:      fun(); goto case;
                    case 6:      fun(); goto case;
                    case 5:      fun(); goto case;
                    case 4:      fun(); goto case;
                    case 3:      fun(); goto case;
                    case 2:      fun(); goto case;
                    case 1:      fun(); continue;
                    default:     assert(0, "Impossible");
                            } while (--n > 0);
                }
            }
        }
    }

    void main()
    {
        int i = 1;
        int j = 11;

        mixin duffs_device!(i, j, delegate { writeln("foo"); });
        duff_loop();  // executes foo() 10 times
    }

## Mixin Scope

The declarations in a mixin are placed in a nested scope and then ‘imported’ into the surrounding scope. If the name of a declaration in a mixin is the same as a declaration in the surrounding scope, the surrounding declaration overrides the mixin one:

    import std.stdio : writeln;

    int x = 3;

    mixin template Foo()
    {
        int x = 5;
        int y = 5;
    }

    mixin Foo;
    int y = 3;

    void main()
    {
        writeln("x = ", x);  // prints 3
        writeln("y = ", y);  // prints 3
    }

If two different mixins are put in the same scope, and each define a declaration with the same name, there is an ambiguity error when the declaration is referenced:

    import std.stdio : writeln;

    mixin template Foo()
    {
        int x = 5;
        void func(int x) { }
    }

    mixin template Bar()
    {
        int x = 4;
        void func(long x) { }
    }

    mixin Foo;
    mixin Bar;

    void main()
    {
        writeln("x = ", x);    // error, x is ambiguous
        func(1);               // error, func is ambiguous
    }

The call to func() is ambiguous because Foo.func and Bar.func are in different scopes.

If a mixin has an Identifier, it can be used to disambiguate between conflicting symbols:

    import std.stdio : writeln;

    int x = 6;

    mixin template Foo()
    {
        int x = 5;
        int y = 7;
        void func() { }
    }

    mixin template Bar()
    {
        int x = 4;
        void func() { }
    }

    mixin Foo F;
    mixin Bar B;

    void main()
    {
        writeln("y = ", y);     // prints 7
        writeln("x = ", x);     // prints 6
        writeln("F.x = ", F.x); // prints 5
        writeln("B.x = ", B.x); // prints 4
        F.func();                  // calls Foo.func
        B.func();                  // calls Bar.func
    }

Alias declarations can be used to overload together functions declared in different mixins:

    mixin template Foo()
    {
        void func(int x) {  }
    }

    mixin template Bar()
    {
        void func(long x) {  }
    }

    mixin Foo!() F;
    mixin Bar!() B;

    alias func = F.func;
    alias func = B.func;

    void main()
    {
        func(1);  // calls B.func
        func(1L); // calls F.func
    }

A mixin has its own scope, even if a declaration is overridden by the enclosing one:

    import std.stdio : writeln;

    int x = 4;

    mixin template Foo()
    {
        int x = 5;
        int bar() { return x; }
    }

    mixin Foo;

    void main()
    {
        writeln("x = ", x);         // prints 4
        writeln("bar() = ", bar()); // prints 5
    }

Templates
Contract Programming
Copyright © 1999-2023 by the D Language Foundation | Page generated by Ddoc on Wed Feb 1 17:27:10 2023