Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Created June 5, 2018 15:21
Show Gist options
  • Save alphaKAI/a5813513956637c4306a5db443894a75 to your computer and use it in GitHub Desktop.
Save alphaKAI/a5813513956637c4306a5db443894a75 to your computer and use it in GitHub Desktop.
Boost.Any in Dlang (inspired by http://d.hatena.ne.jp/pknight/20100325/1269539749)
import std.traits,
std.meta;
class Any {
private {
abstract class _AnyBase {
abstract TypeInfo type();
abstract _AnyBase clone();
}
class _Any(T) : _AnyBase {
T value;
this (T value) {
this.value = value;
}
override TypeInfo type() const {
return typeid(T);
}
override _AnyBase clone() {
return new _Any!T(this.value);
}
~this () {}
}
_AnyBase obj;
}
public:
this(T)(T value) {
this.obj = new _Any!T(value);
}
this () {}
this(Any any_obj) {
if (any_obj.obj !is null) {
this.obj = any_obj.obj.clone();
} else {
this.obj = null;
}
}
Any opAssign(T)(T value) if (!is(T == Any)) {
delete this.obj;
this.obj = new _Any!T(value);
return this;
}
T castTo(T)() {
if (this.obj is null) {
throw new Exception("this object has no value");
}
if ((cast(_Any!T)this.obj) is null) {
throw new Exception("can not cast into incompatible type");
} else {
return (cast(_Any!T)this.obj).value;
}
}
TypeInfo type() {
return this.obj.type;
}
}
import std.stdio;
class K {
int value;
this (int value) {
this.value = value;
}
}
void main() {
Any a = new Any;
a = 10;
writeln(a.type);
writeln(a.castTo!int);
a = [1, 2, 3, 4, 5];
writeln(a.type);
writeln(a.castTo!(int[]));
a = new K(123);
writeln(a.type);
writeln(a.castTo!(K).value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment