Attempt at creating a simpler unique_ptr
Alec Stewart
alec-stewart at protonmail.com
Thu Mar 28 21:57:26 UTC 2019
I'm sure something like this has been posted quite a bit, but I
thought I'd try this for the heck of it.
Looking at unique_ptr.h, oof, that ugly. So this is what I have
so far.
This to note
- since templates can't except function arguments, I thought I'd
make use of alias arguments and AliasSeq
- since optional named arguments aren't a thing, I really have
two options
1. Have Func be null on initialization by, unless something is
passed
2. Make the template variadic
The second of these two might actually be better.
- This is really basic and it's just the sole template at the
moment.
/// Attempt to replicate C++'s unique_ptr, but a lot simpler.
/// Hopefully Better C compatiable as well.
import core.memory : __delete;
import std.stdio : writeln;
import std.typecons;
import std.traits;
import std.meta : AliasSeq;
/// This allows us to pass a function as an argument
/// for our pointer templates, and allows us to test
/// if a function (one that deletes, which we'll have to
/// figure a way to test for that later on) is passed to
/// our UniquePointer.
static auto ref SmartArgs(alias Thing, alias Func)()
{
return Func(Thing);
}
/// The UniquePointer
/// Will delete whatever it references whenever it goes
/// out of scope. Pretty basic at the moment.
struct UniquePointer(alias Thing, alias Func)
{
@disable this();
this(auto Thing, Func = null)
{
auto ptr = &Thing;
auto func = Func.nullable;
static assert(isVoid!ptr, "Cannot use something of an
incomplete type");
static assert(ptr.sizeof > 0, "Cannot use something of an
incomplete type.");
}
~this()
{
static if (!isNull!func && isFunction!func)
{
AliasSeq!(SmartArgs!(func, ptr));
}
else
{
writeln("No deletion function way provided, or what
was provided wasn't a function.");
scope (exit)
__delete(ptr);
}
}
}
This is a probably really complicated way of going about how to
learn to use templates, but I just thought it'd be fun.
More information about the Digitalmars-d-learn
mailing list