Parameter mismatch with ?: operator

O

Old Wolf

My compiler rejects this:

std::string foo()
{
std::string s;
return some_condition() ? s : "";
}

saying that the last two operands of ?: must be the same type.
I have to fix it by changing "" to std::string() .

Is this correct behaviour? I remember reading that the compiler
ought to try implicitly converting one of the operands to the
type of the other.
 
U

upashu2

std::string foo()
{
std::string s;
return some_condition() ? s : "";
}My Compiler is not showing any problem : gcc 3.4.2, vc++7.1
saying that the last two operands of ?: must be the same type. Absolutely right.
I have to fix it by changing "" to std::string() .
It should be implicit conversion.Most probably your compiler either
don't support it or it has a option for it and that option is turned
off.
 
T

Torsten Mueller

Old Wolf said:
std::string foo()
{
std::string s;
return some_condition() ? s : "";
}

saying that the last two operands of ?: must be the same type. I
have to fix it by changing "" to std::string() .

Is this correct behaviour? I remember reading that the compiler
ought to try implicitly converting one of the operands to the type
of the other.

I would also suggest to fix this as you describe it yourself.
Otherwise the compiler looks for an implicit constructor matching a
const char* parameter. If your code is compiled with a STL
implementation using explicit constructors the compiler will not use
even a matching constructor.

I find implicit constructors bad style because people beeing not
familiar with this (especially beginners) don't even know that there's
a constructor and from what class. It's the same with function
parameters.

T.M.
 
W

Wolfgang Forstmeier

In my opinion the compiler is right,
because you had to return an std::string
and "" is not a std::string.

Greetings Wolfgang...
 
O

Old Wolf

Gabriel said:
What compiler do you use?

Borland C++Builder 5 (compiler version 5.5.1).
It looks like it's just a compiler bug then -- the library
(Rogue Wave 2.1.1) doesn't use explicit constructors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top