Last active
June 26, 2020 22:20
-
-
Save v--/5cbd0046be6fc5dbff9a9ad2f1717cde to your computer and use it in GitHub Desktop.
I saw a joke tweet some time ago about encoding natural numbers in levels of pointer indirection and doing arithmetic with them. This is different from what is usually called pointer arithmetic, however it is arithmetic and it involves pointers. I decided to implement addition and multiplication.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/+ dub.sdl: | |
name "pointer_arithmetic" | |
+/ | |
import std.traits : isPointer, PointerTarget; | |
template IndirectionCounter(T) | |
{ | |
static if (isPointer!T) | |
enum IndirectionCounter = 1 + IndirectionCounter!(PointerTarget!T); | |
else | |
enum IndirectionCounter = 0; | |
} | |
static assert(IndirectionCounter!(int) == 0); | |
static assert(IndirectionCounter!(int***) == 3); | |
static assert(IndirectionCounter!(int******) == 6); | |
template Add(T, S) | |
{ | |
static if (isPointer!S) | |
alias Add = Add!(T*, PointerTarget!S); | |
else | |
alias Add = T; | |
} | |
static assert(is(Add!(int, int) == int)); | |
static assert(is(Add!(int*, int) == int*)); | |
static assert(is(Add!(int, int*) == int*)); | |
static assert(is(Add!(int*, int**) == int***)); | |
template Mult(T, S) | |
{ | |
static if (isPointer!S && isPointer!T) | |
alias Mult = Add!(T, Mult!(T, PointerTarget!S)); | |
else static if (isPointer!S) | |
alias Mult = T; | |
else | |
alias Mult = S; | |
} | |
static assert(is(Mult!(int, int) == int)); | |
static assert(is(Mult!(int*, int) == int)); | |
static assert(is(Mult!(int, int*) == int)); | |
static assert(is(Mult!(int*, int**) == int**)); | |
static assert(is(Mult!(int**, int***) == int******)); | |
void main() { | |
import std.stdio: writeln; | |
writeln("Success!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment