On 2012-12-14, 00:19, H. S. Teoh wrote:

I'd like to overload the '*' operator to work with string arguments. Is
it possible? I tried the following, but apparently operator overloading
doesn't work at the package level?

        string opBinary(string op)(string repeatMe, int thisManyTimes)
                if (op=="*")
        {
                auto app = appender!string();
                while (thisManyTimes > 0) {
                        app.put(repeatMe);
                        thisManyTimes--;
                }
                return app.data;
        }

        void main() {
                writeln("spam" * 3);  // compile error
        }

Or is this just a very bad idea? ;-)

Like bearophile said, overloaded operators need to be defined inside
one of the types on which they should operate. Since built-in types
cannot be modified, one cannot overload operators on them.

--
Simen

Reply via email to