Operator overloading of native types?

Jacob Carlborg doob at me.com
Fri Dec 14 04:49:12 PST 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


More information about the Digitalmars-d-learn mailing list