简体   繁体   中英

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

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?

This seems like a compiler bug. I reported it here: fails to find user-defined-conversion in virtual inheritance

Feel free to up vote it so it gets prioritized for fixing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM