Create custom data types

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Apr 29 15:48:42 PDT 2015


On Wednesday, 29 April 2015 at 21:49:08 UTC, Ali Çehreli wrote:
> On 04/29/2015 12:53 PM, Dennis Ritchie wrote:
>
>> On Wednesday, 29 April 2015 at 17:52:27 UTC, Ali Çehreli wrote:
>>> It should be easy to make a template of it. (I really think 
>>> it should
>>> already be in Phobos. :) )
>>
>> Where can I find documentation on this subject?
>
> Once a piece of code works for a particular type or value, it 
> is easy to convert it to a template by moving the type and the 
> value to the template parameter list and replace all 
> occurrences of those with template parameters:
>
> - int -> T
>
> - -32_000 -> minValue
>
> - 32_000 -> maxValue
>
> Here it is:
>
> import std.exception;
>
> struct CustomInteger(T, T minValue, T maxValue)
> {
>     T value_;
>
>     alias value this;
>
>     @property T value() const
>     {
>         enforce((value_ >= minValue) &&
>                 (value_ <= maxValue));
>
>         return value_;
>     }
>
>     @property void value(T v)
>     {
>         value_ = v;
>     }
> }
>
> unittest
> {
>     alias Balance = CustomInteger!(int, -32_000, 32_000);
>
>     auto b = Balance(42);
>     assert(b == 42);
>
>     b = 40_000;
>
>     void foo(int) {}
>     assertThrown(foo(b));
> }
>
> void main()
> {}
>
> Ali

Thanks. And how can I stop all attempts to perform actions 
arifmiticheskih the type int? Ie action to "t += b;" suppressed 
to compile.

-----
import std.exception, std.stdio;

struct CustomInteger(T, T minValue, T maxValue)
{
	T value_;
	
	alias value this;
	
	@property T value() const
	{
		enforce((value_ >= minValue) &&
			(value_ <= maxValue));
		
		return value_;
	}
	
	@property void value(T v)
	{
		value_ = v;
	}
}

void main()
{
	alias Balance = CustomInteger!(int, -32_000, 32_000);
	
	auto b = Balance(42);

	// b += 5; // Error: 'b += 5' is not a scalar,
	// it is a CustomInteger!(int, -32000, 32000)

	int t = 4;

	t += b; // OK

	writeln(b); // prints 46
}


More information about the Digitalmars-d-learn mailing list