www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Operator overloading of native types?

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
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
prev sibling parent Jacob Carlborg <doob me.com> writes:
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