On 05/16/2016 10:39 PM, Alex wrote:
// This function is intentionally templated, as it should take slices
and return something
// boundchecked only
@nogc T[] getSlice(T)(T* ptr, size_t a, size_t b)
{
     return T[a .. b];

Typo here. Should be `ptr[a .. b]`.

}

void main()
{
     void* ptr; // this will stay uninitialized during the whole program
run

The pointer is being initialized, though. To null, which is why your shenanigans below work reliably.

     // something that works as desired:
     writeln(&ptr[4]); // prints '4'
     auto b = getSlice(ptr, 5, 10);
     writeln("b first: ", &b[0]); // prints '5'. This is the most useful
feature.
     assert(b.capacity == 0); // holds always. So, getSlice returns
always a slice, not an array.
     // arr[3] = ... // fails. It is intended to do so.

     // something that does not worked as expected:
     // how to rewrite a for loop
     for(auto i = 0; i < b.length; i++) writeln(&b[i]);
     // into a foreach loop?

Not, I guess, since you can't have a void variable, not even if it's marked `ref`.

I have to say that I don't see the point in all this. You can't access the elements of b in any way, since they're in memory that you don't own. So all you got here is a fancy way of counting, no?

Looping over a range of numbers:
----
foreach (i; 5 .. 10) writeln(i);
----

Or if you want to store it in a variable:
----
import std.range: iota;
auto b = iota(5, 10);
foreach (i; b) writeln(i);
----

     // a question about usability: is there a trait, which can
semantically check, if a type
     // (void, or something else) behaves in the described manner?

Not sure what you mean here. What's the described manner? Not being able to have a variable of the type?

I think void is the only type with that property. So maybe checking if the type is exactly void is enough: `is(T == void)`.

Or you can check if some operation works on the type or a value of it: `__traits(compiles, writeln(T.init))`

}

Reply via email to