Thread overview
Operator overloading of native types?
Dec 13, 2012
H. S. Teoh
Dec 13, 2012
bearophile
Dec 14, 2012
Jacob Carlborg
December 13, 2012
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
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
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