UDAs - Restrict to User Defined Types?

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Thu Nov 8 22:41:12 PST 2012


On Thu, 8 Nov 2012 21:37:00 -0800
"H. S. Teoh" <hsteoh at quickfur.ath.cx> wrote:
> 
> IOW, you want the user-defined type to declare that it's an input
> range, and not just some random struct that happens to have input
> range like functions?
> 

Yes.

> What about modifying isInputRange to be something like this:
> 
> 	template isInputRange(R) {
> 		static if (R.implementsInputRange &&
> 			/* ... check for input range properties here
> */) {
> 			enum isInputRange = true;
> 		} else {
> 			enum isInputRange = false;
> 		}
> 	}
> 
> Then all input ranges will have to explicitly declare they are an
> input range thus:
> 
> 	struct MyInpRange {
> 		// This asserts that we're trying to be an input range
> 		enum implementsInputRange = true;
> 
> 		// ... define .empty, .front, .popFront here
> 	}
> 

Close. At that point you need two steps:

struct MyInpRange {
    // Declare this as an input range
    enum implementsInputRange = true;

    // Enforce this really *IS* as an input range
    static assert(isInputRange!MyRange,
        "Dude, your struct isn't a range!"); // asserts

    // ... define .empty, .front, .popFront here
}

My suggestion was to take basically that, and then wrap up the "Declare
and Enfore" in one simple step:

struct MyInpRange {

    // Generate & mixin *both* the "enum" and the "static assert"
    mixin(implements!InputRange);

    // ... define .empty, .front, .popFront here
}

/Dreaming:

Of course, it'd be even nicer still to have all this wrapped up in
some language sugar (D3? ;) ) and just do something like:

struct interface InputRange {
    // ... *declare* .empty, .front, .popFront here
}

struct interface ForwardRange : InputRange {
    // ... *declare* .save here
}

struct MyForwardRange : ForwardRange {
    // ... define .empty, .front, .popFront, .save here
    // Actually validated by the compiler
}

Which would then amount to what we're doing by hand up above. So kinda
like Go, except not error-prone and ducky and all shitty.



More information about the Digitalmars-d mailing list