Last active
February 20, 2018 07:04
-
-
Save valmat/bdcf24e3365d202aaae7db6ffbf9429d to your computer and use it in GitHub Desktop.
variable destructuring; array to variables list; destructuring assign.
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
module StringManip; | |
import std.range : empty, popFront, front; | |
auto destr(Arg0, Args...)(ref Arg0 arg0, ref Args args) | |
{ | |
return DestrInstance!(Arg0, Args.length+1)(arg0, args); | |
} | |
private struct DestrInstance(T, size_t N) | |
{ | |
this(Args...)(ref T arg0, ref Args args) | |
{ | |
items[0] = &arg0; | |
foreach(i, ref arg; args) { | |
items[i+1] = &arg; | |
} | |
} | |
// overloading assignment operator | |
void opAssign(rhs_t)(rhs_t rhs) | |
{ | |
for (size_t i = 0; !rhs.empty && i < N; rhs.popFront(), ++i) { | |
*items[i] = rhs.front; | |
} | |
} | |
T* [N] items; | |
} | |
nothrow unittest { | |
string a, b, c; | |
destr(a,b,c) = ["foo1","foo2","foo3","foo4"]; | |
assert([a,b,c] == ["foo1", "foo2", "foo3"]); | |
destr(a,b,c) = ["bar1","bar2"]; | |
assert([a,b,c] == ["bar1", "bar2", "foo3"]); | |
} |
Author
valmat
commented
Feb 13, 2018
•
- Compare with the same C++ implementation: https://gist.github.com/valmat/455d9f9c56237b87f7e2
- run this code: https://run.dlang.io/is/472Dq2
I have written an other implementation that also can retrieve variables for iterable types and tuples:
https://gist.github.com/valmat/763c72465d7a1737229ae1c91393d629
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment