Create custom data types
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Apr 29 10:52:27 PDT 2015
On 04/29/2015 10:17 AM, Dennis Ritchie wrote:
> Hi,
> Is it possible to create simple D user-defined data types without the
> use of classes and other OOP?
>
> For example, in Ada is done as follows:
>
> -----
> type balance is new Integer range -32_000 .. 32_000;
Something similar to the following solution should be in Phobos:
import std.exception;
struct Balance
{
int value_;
alias value this;
@property int value() const
{
enforce((value_ >= -32_000) &&
(value_ <= 32_000));
return value_;
}
@property void value(int v)
{
value_ = v;
}
}
unittest
{
auto b = Balance(42);
assert(b == 42);
b = 40_000;
void foo(int) {}
assertThrown(foo(b));
}
void main()
{}
It should be easy to make a template of it. (I really think it should
already be in Phobos. :) )
It can be different in several ways: If mutation is never allowed, then
the range enforcement can be moved to its constructor. Otherwise, if
mutation is allowed and used much less than access, then the enforcement
can be moved to the setter.
Ali
More information about the Digitalmars-d-learn
mailing list