digitalmars.D.learn - Operator overloading of native types?
- H. S. Teoh (20/20) Dec 13 2012 I'd like to overload the '*' operator to work with string arguments. Is
- bearophile (5/7) Dec 13 2012 In D the overloaded operators need to be defined inside
- Jacob Carlborg (8/25) Dec 14 2012 The closest you can get is to wrap, in this case, a string in a struct.
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? ;-) T -- Старый друг лучше новых двух.
Dec 13 2012
H. S. Teoh:but apparently operator overloading doesn't work at the package level?In D the overloaded operators need to be defined inside structs/classes. Bye, bearophile
Dec 13 2012
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? ;-)The closest you can get is to wrap, in this case, a string in a struct. Add an "alias this" and the operators you want to overload. Then you can do something like: writeln(String("spam") * 3); Not as pretty or convenient. -- /Jacob Carlborg
Dec 14 2012