quack ~master
A compile-time duck typing library for D
To use this package, run the following command in your project's root directory:
Manual usage
Put the following dependency into your project's dependences section:
quack
A library for enabling compile-time duck typing in D.
Duck Typing
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.
Usage
Duck exists so that you may treat non-related types as polymorphic, at compile time. There are three primary ways to use quack:
1) 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 to
alias this
.
2) Storing pointers to objects: For this, you should use a DuckPointer!A
,
which can be created with duck!A( B b )
, assuming B "extends" A (the actual
check is done using extends
, 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.
3) Checking for the presence of a mixin: For this, you'll want
hasStringMixin!( A, mix )
or hasTemplateMixin!( 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
.
Examples
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() );
}
- Registered by Colden Cullen
- ~master released 4 years ago
- ColdenCullen/quack
- MIT
- Copyright © 2014, Colden Cullen
- Authors:
- Dependencies:
- tested
- Versions:
-
1.0.0 2014-Aug-16 0.4.0 2014-Aug-03 0.3.0 2014-Aug-02 0.2.0 2014-Aug-02 0.1.0 2014-Aug-01 - Download Stats:
-
-
0 downloads today
-
0 downloads this week
-
0 downloads this month
-
263 downloads total
-
- Score:
- 0.8
- Short URL:
- quack.dub.pm