Ambiguous user-defined-conversion in Visual C++ (VS2017)

  • Thread starter Thread starter Artem Diatlov
  • Start date Start date
A

Artem Diatlov

Guest
VS2017 (15.8.7/15.8.8) fails to compile code like this:

#include <iostream>

class A
{
public:
operator int() const { std::cout << "int() 1" << std::endl; return 0; }
operator int() { std::cout << "int() 2" << std::endl; return 0; }
};

class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

int main()
{
// Compiles when const version is defined before non-const.
// The assignment calls const version of course.
const D cobj;
int i = cobj;

// Compiles when non-const version is defined before const.
// The assignment calls non-const version.
D obj;
int j = obj;

return 0;
}

Errors:

  1. error C2440: 'initializing': cannot convert from 'D' to 'int'
  2. note: Ambiguous user-defined-conversion

g++ 7.3 (by default and with std=c++11/14/17) and VS2013 (update 5) compiles this without any warnings/errors related to conversion functions (even with -Wall).

Why the code is ambiguous? Is this a VC++ bug?

Continue reading...
 
Back
Top