Menu
Home
Create new Paste
Log in
Code
Theme: cobalt
Theme: eclipse
Theme: elegant
Theme: monokai
Theme: neat
Theme: night
Theme: rubyblue
import std.stdio; import std.traits : CommonType; struct Numeric { private: union Num { float fvalue; int ivalue; } alias CommonType!(int, float) NumType; final enum Type { None, Float, Int } Num _num; Type _type; private: void _assign(T)(T val) { static if (is(T : int)) { //writeln("foo : ", val); this._type = Type.Int; this._num.ivalue = val; } else if (is(T : float)) { //writeln("bar : ", val); this._type = Type.Float; this._num.fvalue = val; } else { throw new Exception("Undefined number type."); } } public: this(T)(T val) { this._assign(val); } typeof(this) opAssign(T)(T val) { this._assign(val); return this; } @property //auto get() const { NumType get() const { //write(" -> ", this._type, " : "); switch (this._type) { case Type.Int: return this._num.ivalue; case Type.Float: return this._num.fvalue; default: return 0; } } alias get this; ref Numeric opOpAssign(string op, T)(T val) { NumType _val; switch (this._type) { case Type.Int: _val = this._num.ivalue; break; case Type.Float: _val = this._num.fvalue; break; default: return this; } switch (op) { case "+": _val += val; break; case "-": _val -= val; break; case "/": _val /= val; break; case "*": _val *= val; break; case "%": _val %= val; break; case "^^": _val ^^= val; break; default: break; } switch (this._type) { case Type.Int: this._num.ivalue = cast(int) _val; break; case Type.Float: this._num.fvalue = _val; default: break; } return this; } } void main() { Numeric zahl; writeln("zahl starts with ", zahl); zahl = 3.14; float f = zahl; writeln(" => ", f); writeln("zahl is ", zahl); zahl = 42; writeln("zahl is now ", zahl); int i = cast(int) zahl; writeln("####"); Numeric next = zahl; writeln(next); next += zahl; writeln(next); writeln("####"); Numeric nextnext = next + zahl; writeln(nextnext); writeln("----"); writeln(Numeric.sizeof); }
Result:
Success
/
Return code: 0
/
Compilation time:
0.316
seconds
/
Run time:
0.001
seconds
Application output:
zahl starts with 0
=> 3.14
zahl is 3.14
zahl is now 42
####
42
84
####
126
----
8
Username
Message
Add comment
Paste info
Author:
Namespace
Views:
109
Private:
no
Expires:
Never
Uploaded:
11.09.12 22:32
Votes
:
0
Tweet
Compilation
Compiler:
DMD 2.060
Pointer size:
m64
Actions
Download
Fork
Raw
×
Confirm
Are you sure you want to delete this paste?
There's no way back!
×
Confirm
Reason