'strong types' a la boost
Charles Cooper via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Mar 14 09:55:08 PDT 2015
Interesting. I think in the second example there are pathological
cases where one has similar declarations in two modules at the
same line.
moduleA.d:100
alias dollars_t TypeDef!int;
moduleB.d:100
alias cents_t TypeDef!int;
main.d:
import moduleA;
import moduleB;
void write_dollars_to_database(dollars_t x) {
/* code */
}
void main() {
cents_t cents;
write_dollars_to_database(cents); // compilation succeeds, bank
fails
}
However, I see your point, I think it can be gotten around by
using a combination of the __LINE__, __FILE__ and __MODULE__
directives!
Charles
On Saturday, 14 March 2015 at 16:01:15 UTC, Namespace wrote:
> You can do it this way:
> ----
> struct dollars_t {
> uint _dollar;
>
> this(uint d) {
> _dollar = d;
> }
>
> alias _dollar this;
> }
>
> struct cents_t {
> uint _cent;
>
> this(uint c) {
> _cent = c;
> }
>
> alias _cent this;
> }
>
> void do_something_with_dollars(dollars_t d) {
> writeln(d);
> }
>
> void main() {
> dollars_t d = 1;
>
> do_something_with_dollars(d);
>
> cents_t c = 2;
>
> //do_something_with_dollars(c);
> //do_something_with_dollars(2);
> }
> ----
>
> Or you can create your own small TypeDef:
>
> ----
> struct TypeDef(T, size_t l = __LINE__) {
> T _val;
>
> this(T v) {
> _val = v;
> }
>
> alias _val this;
> }
>
> alias dollars_t = TypeDef!(uint);
> alias cents_t = TypeDef!(uint);
> ----
>
> Thanks to the second template parameter 'l' the template
> instances of dollars_t and cents_t aren't equal.
More information about the Digitalmars-d-learn
mailing list