String and opBinary

Eyyub eyyub.pangearaion at gmail.com
Fri Jun 1 13:18:50 PDT 2012


On Friday, 1 June 2012 at 19:37:38 UTC, Zhenya wrote:
> This code work
>
> import std.stdio;
>
> struct String
> {
> 	string data;
> 	alias data this;
> 	this(string s)
> 	{
> 		data = s;
> 	}
> 	String opBinary(string op : "*")(string word)
> 	{
> 		string temp;
> 		foreach(letter; word)
> 		{
> 			temp ~= data;
> 		}
> 		return String(temp);
> 	}
> };
>
> string opBinary(string op : "*")(string data, string word)
> {
> 	string temp;
> 	foreach(letter; word)
> 	{
> 		temp ~= data;
> 	}
> 	return temp;
> }
>
> void main()
> {
> 	String word = "foo";
> 	String secretword = String("_") * word;
>  	//string secretword = "_".opBinary!"*"(word); // compile
> 	writeln(secretword); // output : ___
> }

Hi Zhenya, thanks for your reply !

I considered using this tip but that doesn't look nice compared 
to the C++ way does it. :/

Why doesn't D allow a way to write operator overloading at 
scope-module level like in C++ ?(in this case)

(Thanks for your tip Dmitry)


More information about the Digitalmars-d-learn mailing list