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);
}
@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