Thread overview | |||||
---|---|---|---|---|---|
|
December 13, 2012 Operator overloading of native types? | ||||
---|---|---|---|---|
| ||||
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
--
Старый друг лучше новых двух.
|
December 13, 2012 Re: Operator overloading of native types? | ||||
---|---|---|---|---|
| ||||
Posted in reply to H. S. Teoh | 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
|
December 14, 2012 Re: Operator overloading of native types? | ||||
---|---|---|---|---|
| ||||
Posted in reply to H. S. Teoh | 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 |
Copyright © 1999-2021 by the D Language Foundation