Create custom data types
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Apr 29 14:49:07 PDT 2015
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
More information about the Digitalmars-d-learn
mailing list