On 20/01/16 11:41 PM, chardetm wrote:
Hi everyone,

I was wondering if it was possible to know at compile time if opSlice is
defined for a type, including built-in types like "string". Here is the
code I have:


import std.stdio;

struct Test {
     Test opSlice(size_t i, size_t j) {
         return this; // We don't care what it returns
     }
}

void main () {
     string s = "Hello";
     auto s2 = s[0..2];
     static if (is(typeof(&string.opSlice))) writeln("Ok string");

     Test t;
     auto t2 = t[0..2];
     static if (is(typeof(&Test.opSlice))) writeln("Ok Test");
}

Output:
Ok Test


How to make it work for "string" too (if possible)? And is there a way
to differentiate "opSlice()" from "opSlice(size_t, size_t)" (or
"opSlice(T, T)" for any T)?

Thank you in advance!

template CanSlice(T) {
enum CanSlice = __traits(compiles, {T t; auto v = t[0 .. 1];}) || __traits(compiles, {T t; auto v = t.opSlice();});
}

Should work.

Reply via email to