String and opBinary
Jonathan M Davis
jmdavisProg at gmx.com
Fri Jun 1 12:02:14 PDT 2012
On Friday, June 01, 2012 19:51:35 Eyyub wrote:
> Hi,
>
> I'd like to know why this following code doesn't compile :
>
> string opBinary(string op : "*")(string data, string word)
> {
> string temp;
> foreach(letter; word)
> {
> temp ~= data;
> }
> return temp;
> }
>
> void main()
> {
> string word = "foo";
> string secretword = "_" * word; //Error: '"_"' is not of
> arithmetic type it is a string
> //Error: 'word' is not of arithmetic type, it is a string
> string secretword = "_".opBinary!"*"(word); // compile
> writeln(secretword); // output : ___
> }
>
> Even more weird, with just another op specialisation but the same
> function's body :
> string opBinary(string op : "+")(string data, string word)
> {
> string temp;
> foreach(letter; word)
> {
> temp ~= data;
> }
> return temp;
> }
>
> void main()
> {
> string word = "foo";
> string secretword = "_" + word; // Error: Array operation "_" -
> word not implemented // why the error message is not the same
> with different op ?
> string secretword = "_".opBinary!"+"(word); // this works fine
> }
>
> Thanks,
>
> (sorry for my bad english)
I don't believe that it's legal to declare overloaded operators for built-in
types. So, it's not legal to do what you're trying to do. You can call the
function directly, because it's a valid function, but it isn't used to
overload any operators.
As for why you're getting a complaint about subtraction in the second example,
I don't know. Running the current, development version from github I get a +,
so it may be a bug in whatever version of the compiler that you're using that
has since been fixed.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list