Skip to content

Instantly share code, notes, and snippets.

@thedeemon
Last active April 20, 2020 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedeemon/169756a1b9c10283801bc588a8f65f60 to your computer and use it in GitHub Desktop.
Save thedeemon/169756a1b9c10283801bc588a8f65f60 to your computer and use it in GitHub Desktop.
import std.stdio;
// secret sauce: https://dlang.org/spec/class.html#alias-this
struct DayNum {
int dn;
alias dn this; // this line makes DayNum look like an int with dn as the value
}
DayNum next(DayNum d) {
int inty = d + 1; // this is ok, a DayNum can be used as an int
return DayNum(inty); // conversion from int to DayNum still needs to be explicit
}
void main() {
auto n = next( DayNum(2) );
//auto n = next( 2 ); // this will not compile, 2 is not a DayNum
writeln(n);
}
@julian-wiseman
Copy link

julian-wiseman commented Apr 16, 2020

Please allow a more cunning alias question.

struct bondNotLive
{
	Date settle ;
	Date maturity ;
	double coupon ;
	double accrued ;
}

struct bond
{
	immutable bondNotLive bnl;
	double cleanPrice ;
	double dirtyPrice ;
	double yieldAnnual ;
}

bond b ;

It is possible to access the maturity with something like b.bnl.maturity . Can all the parts of bnl be aliased into the type bond, such that they can be accessed in the form b.maturity?

(The plan is that immutable financial instruments are built once per day, without their prices. Prices and consequences can be updated, even as the immutable bits remain immutable.)

@thedeemon
Copy link
Author

Same answer basically:

struct bondNotLive
{
	Date settle ;
	Date maturity ;
	double coupon ;
	double accrued ;
}

struct bond
{
	immutable bondNotLive bnl;
	double cleanPrice;
	double dirtyPrice;
	double yieldAnnual;

	alias bnl this; // <---
}

void main() {
	auto bn = bondNotLive(Date(2020, 4, 5), Date(2020,4,7), 12, 13);
	auto b = bond(bn, 2, 3, 4);
	writeln(b.coupon); // ok, says 12
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment