View source code
Display the source code in std/typecons.d from which this page was generated on github.
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 local clone.

Class std.typecons.AutoImplement

AutoImplement automatically implements (by default) all abstract member functions in the class or interface Base in specified way.

class AutoImplement(Base, alias how, alias what)
  
if (!is(how == class));
class AutoImplement(Interface, BaseClass, alias how, alias what)
  
if (is(Interface == interface) && is(BaseClass == class));

The second version of AutoImplement automatically implements Interface, while deriving from BaseClass.

Methods

NameDescription
factory (classname) Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor.
opCmp (o) Compare with another Object obj.
opEquals (o) Test whether this is equal to o. The default implementation only compares by identity (using the is operator). Generally, overrides and overloads for opEquals should attempt to compare objects by their contents. A class will most likely want to add an overload that takes your specific type as the argument and does the content comparison. Then you can override this and forward it to your specific typed overload with a cast. Remember to check for null on the typed overload.
toHash () Compute hash function for Object.
toString () Convert Object to a human readable string.

Methods

NameDescription
factory (classname) Create instance of class specified by the fully qualified name classname. The class must either have no constructors or have a default constructor.
opCmp (o) Compare with another Object obj.
opEquals (o) Test whether this is equal to o. The default implementation only compares by identity (using the is operator). Generally, overrides and overloads for opEquals should attempt to compare objects by their contents. A class will most likely want to add an overload that takes your specific type as the argument and does the content comparison. Then you can override this and forward it to your specific typed overload with a cast. Remember to check for null on the typed overload.
toHash () Compute hash function for Object.
toString () Convert Object to a human readable string.

Parameters

NameDescription
how template which specifies how functions will be implemented/overridden. Two arguments are passed to how: the type Base and an alias to an implemented function. Then how must return an implemented function body as a string. The generated function body can use these keywords:
  • a0, a1, …: arguments passed to the function;
  • args: a tuple of the arguments;
  • self: an alias to the function itself;
  • parent: an alias to the overridden function (if any).
You may want to use templated property functions (instead of Implicit Template Properties) to generate complex functions: -------------------- // Prints log messages for each call to overridden functions. string generateLogger(C, alias fun)() @property { import std.traits; enum qname = C.stringof ~ "." ~ __traits(identifier, fun); string stmt; stmt ~= q{ struct Importer { import std.stdio; } }; stmt ~= `Importer.writeln("Log: ` ~ qname ~ `(", args, ")");`; static if (!__traits(isAbstractFunction, fun)) { static if (is(ReturnType!fun == void)) stmt ~= q{ parent(args); }; else stmt ~= q{ auto r = parent(args); Importer.writeln("--> ", r); return r; }; } return stmt; } --------------------
what template which determines what functions should be implemented/overridden. An argument is passed to what: an alias to a non-final member function in Base. Then what must return a boolean value. Return true to indicate that the passed function should be implemented/overridden. -------------------- // Sees if fun returns something. enum bool hasValue(alias fun) = !is(ReturnType!(fun) == void); --------------------

Note

Generated code is inserted in the scope of std.typecons module. Thus, any useful functions outside std.typecons cannot be used in the generated code. To workaround this problem, you may import necessary things in a local struct, as done in the generateLogger() template in the above example.

BUGS

  • Variadic arguments to constructors are not forwarded to super.
  • Deep interface inheritance causes compile error with messages like "Error: function std.typecons.AutoImplement!(Foo).AutoImplement.bar does not override any function". [Bugzilla 2525]
  • The parent keyword is actually a delegate to the super class' corresponding member function. [Bugzilla 2540]
  • Using alias template parameter in how and/or what may cause strange compile error. Use template tuple parameter instead to workaround this problem. [Bugzilla 4217]

Example

interface PackageSupplier
{
    int foo();
    int bar();
}

static abstract class AbstractFallbackPackageSupplier : PackageSupplier
{
    protected PackageSupplier default_, fallback;

    this(PackageSupplier default_, PackageSupplier fallback)
    {
        this.default_ = default_;
        this.fallback = fallback;
    }

    abstract int foo();
    abstract int bar();
}

template fallback(T, alias func)
{
    import std.format : format;
    // for all implemented methods:
    // - try default first
    // - only on a failure run & return fallback
    enum fallback = q{
        try
        {
            return default_.%1$s(args);
        }
        catch (Exception)
        {
            return fallback.%1$s(args);
        }
    }.format(__traits(identifier, func));
}

// combines two classes and use the second one as fallback
alias FallbackPackageSupplier = AutoImplement!(AbstractFallbackPackageSupplier, fallback);

class FailingPackageSupplier : PackageSupplier
{
    int foo(){ throw new Exception("failure"); }
    int bar(){ return 2;}
}

class BackupPackageSupplier : PackageSupplier
{
    int foo(){ return -1; }
    int bar(){ return -1;}
}

auto registry = new FallbackPackageSupplier(new FailingPackageSupplier(), new BackupPackageSupplier());

writeln(registry.foo()); // -1
writeln(registry.bar()); // 2

Authors

Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara

License

Boost License 1.0.