pad.mattdiesel.co.uk

Snippet - Variant struct in D

Variant struct in D (D)

First attempt at a variant structure in D, with int and float types.
Created 2014-04-10 13:34:42.225260 by Matt.
Modified 2014-04-10 13:36:35.759010 by Matt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import std.stdio; // writeln
import std.conv; // to!
import std.string; // format, wstring

enum varType {
	None,
	Int,
	Float
}

union varData {
	int asInt;
	float asFloat;
}

struct variant {
private:
	varType _type;
	varData _data;

	// Getters:
	T get(T)() const {
		switch(this._type) {
			case varType.None:
				return( T.init );
			case varType.Int:
				return( this.getInt!(T)( ) );
			case varType.Float:
				return( this.getFloat!(T)( ) );
			default:
				throw new Exception("Unknown Type");
		}
	}

	T getInt(T)() const {
		return( to!(T)(this._data.asInt) );
	}

	T getFloat(T)() const {
		return( to!(T)(this._data.asFloat) );
	}

	// Not very useful, but an example of how specialization could be used for
	// custom conversions.
	int getFloat(T : int)() const {
		return( 123 );
	}

	// Setters:
	void set(T)(T value) {
		throw new Exception(format("Don't know how to set to type %s.", T.stringof));
	}

	void set(T : int)(int value) {
		this._type = varType.Int;
		this._data.asInt = value;
	}

	void set(T : float)(float value) {
		this._type = varType.Float;
		this._data.asFloat = value;
	}

public:
	@property {
		T Value(T)() const {
			return( this.get!(T)() );
		}

		void Value(T)(T value) {
			this.set!(T)(value);
		}
	}
}



void main() {
	variant v;

	writeln("Empty variant:");
	writeln(v.Value!(int));
	writeln(v.Value!(float));
	writeln(v.Value!(wstring));

	v.Value = 42.3f;
	//v.Value!(float) = 42.3f; // Or explicitly

	writeln("After setting to float:");
	writeln(v.Value!(int));
	writeln(v.Value!(float));
	writeln(v.Value!(wstring));

	// v.Value!(wstring) = "42.3"w; // This will throw an exception.
}