A library for enabling compile-time duck typing in D.
Duck typing is a reference to the phrase "if it walks like a duck, and quacks
like a duck, then it's probably a duck." The idea is that if a struct
or
class
has all the same members as another, it should be usable as the other.
Duck exists so that you may treat non-related types as polymorphic, at compile time. There are three primary ways to use quack:
-
Taking objects as arguments: For this, you should use
extends!( A, B )
, which returns true if A "extends" B. It can do this by implementing all of the same members B has, or by having a variable of type B that it has set toalias this
. -
Storing pointers to objects: For this, you should use a
DuckPointer!A
, which can be created withduck!A( B b )
, assuming B "extends" A (the actual check is done usingextends
, so see the docs on that). Note that this approach should only be used when you need to actually store the object, as it is much slower than the pure template approach. -
Checking for the presence of a mixin: For this, you'll want
hasStringMixin!( A, mix )
orhasTemplateMixin!( A, mix )
. These two templates will instantiate a struct with the given mixin,mix
, and check if it is compatible with the type given,A
.
import quack;
import std.stdio;
struct Base
{
int x;
}
struct Child1
{
Base b;
alias b this;
}
struct Child2
{
int x;
}
void someFunction( T )( T t ) if( extends!( T, Base ) )
{
writeln( t.x );
}
struct HolderOfBase
{
DuckPointer!Base myBase;
}
void main()
{
someFunction( Child1() );
someFunction( Child2() );
auto aHolder1 = new HolderOfA( duck!Base( Child1() ) );
auto aHolder2 = new HolderOfA( duck!Base( Child2() ) );
}
import quack;
import std.stdio;
enum myStringMixin = q{
void stringMember();
};
mixin template MyTemplateMixin( MemberType )
{
MemberType templateMember;
}
void doAThing( T )( T t ) if( hasTemplateMixin!( T, MyTemplateMixin, float ) )
{
// Doing a thing...
}
void doAnotherThing( T )( T t ) if( hasStringMixin!( T, myStringMixin ) )
{
// Still doing things...
}
struct TemplateMixinImpl
{
mixin MyTemplateMixin!float;
}
struct StringMixinImpl
{
mixin( myStringMixin );
}
void main()
{
doAThing( TemplateMixinImpl() );
doAnotherThing( StringMixinImpl() );
}