Could anyone help me understand why the below code doesn’t compile (VS2010) when the getters are const ?
Here’s the test code:
#include <boost/system/error_code.hpp>
class socket {
public:
// setter - throw exception version
void non_blocking(bool mode)
{
// ...
}
// getter - error code version
bool non_blocking(boost::system::error_code& ec) const
{
// ...
}
// setter - error code version
void non_blocking(bool mode, boost::system::error_code& ec)
{
// ...
}
// getter - throw exception version
bool non_blocking() const
{
// ...
}
};
int main()
{
socket s;
boost::system::error_code ec;
bool result = s.non_blocking(ec);
return 0;
}
I know that boost::system::error_code is convertible to bool but can’t understand why the const cause the ambiguity. Here’s the error message from VS2010:
1>c:\projects\pcap++\trunk\main.cpp(145): error C2666: 'socket::non_blocking' : 2 overloads have similar conversions
1> c:\projects\pcap++\trunk\main.cpp(134): could be 'bool socket::non_blocking(boost::system::error_code &) const'
1> c:\projects\pcap++\trunk\main.cpp(129): or 'void socket::non_blocking(bool)'
1> while trying to match the argument list '(boost::system::error_code)'
1> note: qualification adjustment (const/volatile) may be causing the ambiguity
For the purpose of overload resolution, the parameter list of the two overloads are
class socket &, boolandconst class socket &, boost::system::error_code &.The calling parameters are
class socket &, boost::system::error_code &To match the first overload, the following conversion is needed:
In C++0x 13.3.3p1 :
From this, we can see the neither of the match of the two overloads fits this requirement. For the one function, one conversion sequence is better and one conversion is worse than the corresponding conversion sequence of the other function, so the viable function cannot be determined.
If the second overload is not
const, then the conversion sequence for the second overload does not need any conversion (both are identical), so this is better than the other overload, thus no ambiguity.