20
string aux;
int maxy,auxx=0;

cin>>aux;

maxy= (int)sqrt(aux.size());

I'm geting:

1> error C2668: 'sqrt' : ambiguous call to overloaded function
1>        could be 'long double sqrt(long double)'
1>        or       'float sqrt(float)'
1>        or       'double sqrt(double)'

Why?

pickypg
  • 22,034
  • 5
  • 72
  • 84
andandandand
  • 21,946
  • 60
  • 170
  • 271

4 Answers4

33

string::size() returns size_t, and sqrt doesn't accept it in any of its versions. So the compiler has to cast, and cannot choose to what - all of them are OK. You have to put explicit cast:

maxy = (int)sqrt((double)aux.size());
littleadv
  • 20,100
  • 2
  • 36
  • 50
14

The problem is that in C++, there are three functions named sqrt - one taking in a float, one taking a double, and one taking a long double. When you try calling

sqrt(aux.size());

The compiler tries to determine which of these functions you want to call. Since aux.size() returns a string::size_type, which is neither a float, double, nor long double, it tries to see if string::size_type is implicitly convertible to any of these three. But since string::size_type is convertible to all three of these types, the compiler marks the call as ambiguous, since it's unclear which of the conversions you want to do.

To fix this, you can explicitly cast aux.size() to the type that you want. For example:

sqrt(double(aux.size()));

or

sqrt(float(aux.size()));

This makes the call unambiguously match one of the two functions. Depending on the precision you want, you can choose any of the three overloads. Since you're just casting back to an int, it's probably fine to cast to a float here.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 1
    "An unmatched left parenthesis creates an unresolved tension that will stay with you all day" http://xkcd.com/859/ That's why I prefer C-style casts for cases like this one - they produce less levels of nesting. – AnT stands with Russia Jun 03 '11 at 22:13
1

aux.size() returns an std::size_t, but sqrt() does not have an overloaded version that takes a std::size_t argument.

The compiler reports that sqrt has 3 overloads: which take float, double and long double arguments. std::size_t could be converted to any of those, so there's an ambiguity since the compiler doesn't know whether to convert std::size_t to float or double or long double.

Gregg
  • 3,236
  • 20
  • 15
0

Try casting your aux.size() to one of those types, so it won't be ambiguous...

david van brink
  • 3,604
  • 1
  • 22
  • 17