|
|
On 8/1/2011 14:50, Warp wrote:
> It depends on the compiler. Some compilers, especially the slightly older
> ones, don't make such checks.
gcc has been doing it for ages. (Since I haven't used gcc to do a printf in
ages, and I remember doing it... :-) But yeah, I meant more that it's
theoretically pretty easy to cover that case.
> Of course the major problem with the printf-style of I/O is that it breaks
> abstraction, even in C.
Yeah, I guess "breaks abstraction" is more precise than "typesafe". More
like "type change safe." I remember being annoyed when there were no printf
codes for things like size_t and diff_t and so on.
I think C# actually came up with quite a sweet compromise. (Well, maybe not
came up with, maybe "stole", but it's pretty good anyway.) You put in
something like
output.write("blah {0:x} blah {2:y} blah {1:0,000.00}", a, b, c);
that calls a.ToString("x") then c.ToString("0,000.00") then b.ToString("y")
and inserts the results in the appropriate place. That way you don't have
problems like cout<<hex maybe leaving the stream screwed up, and each custom
type can configure its own meaning for formatting strings. It's typesafe and
abstraction safe, *and* it lets you put the formatting strings in a database
for internationalization.
Of course, C# turns each thing into a string and then outputs it, instead of
outputting them bit by bit, but one could work the same sort of API with a
stream interface instead of a string interface.
There's also a slightly weird thing where something different gets called
depending on whether it's one letter after the colon, multiple letters after
the colon, multiple colons, or something like that. I don't remember the
details at this point.
There's also an implicit locale passed in, so you can seamlessly have
multiple concurrent locales and have all the formatting stuff do the right
thing, pick the right date and comma format, pick the right character
encoding, etc. The trick is the locale goes in as another argument to
ToString(), so you can use as many different locales as you want. I never
really learned it well enough to understand all the combinations possible, tho.
> What to put as a format? Even if you put "%i" and have it work ok, it
> breaks the abstraction of MySpecialInt because now you can't change it
> without breaking the printf.
Last time I had to do something like that, I used
typedef int MySpecialInt;
#define MySpecialIntFmt "%i"
and then
printf("Here are " MySpecialIntFmt " integers", i);
But yeah, that was way uglier than it needed to be, especially if you needed
to start putting the strings in an localization file, which is the point to
start with. :-)
--
Darren New, San Diego CA, USA (PST)
How come I never get only one kudo?
Post a reply to this message
|
|