Statically forbid string ~ size_t ?

Don nospam at nospam.com
Thu Oct 13 15:34:35 PDT 2011


On 13.10.2011 23:07, bearophile wrote:
> This comes from a thread in D.learn.
>
> This is a small Python2 program:
>
>
> from sys import argv
> x = len(argv)
> s = "hello"
> s += x
> print s
>
>
> Python is strongly typed so it refuses to append an integer number to a string:
>
> Traceback (most recent call last):
>    File "...\test.py", line 4, in<module>
>      s += x
> TypeError: cannot concatenate 'str' and 'int' objects
>
>
> In Java if you append an integer number to a string the integer number gets first converted to a string:
>
>
> class Main {
>      public static void main(String[] args) {
>          int x = args.length;
>          String s = "hello";
>          s += x;
>          System.out.println(s);
>      }
> }
>
>
> That Java code outputs:
>
> hello0
>
>
> Both Java and Python are far more commonly known than D, and they shape programmers expectations a bit.
>
> This D2 code compiles and runs with DMD 2.056head:
>
>
> void main(string[] args) {
>      int x = args.length;
>      string s = "hello";
>      s ~= x;
> }
>
>
>
> (In this case Python2 is typed more strongly than D.)
>
> I think that int+char is acceptable in D, but string~size_t is not good. I think this is bug prone (especially given the expectations of programmers coming from other languages). So I suggest to statically disallow string~size_t. string~char, string~dchar, and string~string are of course OK.
>
> So far I have written no enhancement request/bug report on this because I am not so sure...

The problem is things like:
int i;
string s = "0x" ~ ('0' + x);
since char + int --> int.



More information about the Digitalmars-d mailing list