Would be prettier as a language feature, but still:

template test(alias pred)
{
    import std.functional : unaryFun;
    alias P = unaryFun!pred;

    auto test(R)(R r)
    {
        struct Test
        {
            R v;

            string toString()
            {
                import std.conv : to;
                return v.to!string;
            }

            bool opCast(B : bool)() const
            {
                return P(v);
            }

            ref inout(R) get() inout
            {
                return v;
            }

            alias get this;
        }

        import std.algorithm : move;
        return Test(move(r));
    }
}

void main()
{
    import std.regex;
    import std.stdio;
    string s1 = "hello";
    string s2 = "world";

    if (auto x = test!"!a.empty"(match(s1, "hello")))
    {
        writeln(x.captures[0]);
    }

    if (auto x = test!"!a.empty"(match(s2, "hello")))
    {
        writeln(x.captures[0]);
        assert(0);
    }

    // UFCS:

    if (auto x = s1.match("world").test!"!a.empty")
    {
        writeln(x.captures[0]);
        assert(0);
    }

    if (auto x = s2.match("world").test!"!a.empty")
    {
        writeln(x.captures[0]);
    }

    if (auto x = 3.test!"a == 3")
    {
        writeln(x, " equals 3, huh?");
    }
}

Reply via email to