Boost logo

Boost :

From: Samuel Krempp (krempp_at_[hidden])
Date: 2003-04-23 08:22:46

Le mer 23/04/2003 à 10:45, Giovanni Bajo a écrit :

> The conversion to string does occur, I tried it in real code, you just need
> a string context:
> void Foo(std::string m)
> { cout << m; }
> Foo("This %s work - %u" % "does" % 123)

Are you sure this is enough to insure the compiler converts the const char[] 's
to string ?? my g++ does not, and I think he's right : the string expected by Foo is
a hint for the expected value returned by the operator%, but the return value is not
taken into account when looking for the candidate function to call,
so I dont see why this should work.

I think the only way is explicitly constructing a string at some point :
cout << string("This %s work - %u") % "does" % 123) ;
And that's at least as ugly as current boost.format.

Even then, the fact you dont have control on std::string means trouble, as Daryle said.

for example :
imagine a user decides to extend the concatenation operator+(string, X)
[ with X= string and char]

by defining :
template<class T>
string operator+(string s , T x) {
        return s+lexical_cast<string> (x) ;

which, though risky because it's a first step to bad conversion+overload troubles,
makes a lot of sense and could happen in real life.
    int x=4,y=10;
    cout << ( std::string(" x+y = _%d") % x+y ) << "_\n";

oops, I meant
    cout << ( std::string(" x+y = _%d") % (x+y) ) << "_\n";

but I forgot parentheses around x+y. this will still compile, using
operator+(string, int) for +y.
expected :
"x+y = _14_"
result :
"x+y = _410_"

uh oh, wrong value displayed, hard to detect.

Having a format object allows this error to be detected at compile-time.
(because we are sure there should never be such a thing as an operator+(format, int) )

Unless you supply implicit format -> string conversion.
so in fact this example shows a possible issue with any implictly convertible format class.
and for me, it's a reason enough to ban implicit conversions..


Boost list run by bdawes at, gregod at, cpdaniel at, john at