编译器错误 C2666

“identifier”:数字重载具有类似的转换

重载函数或运算符不明确。 形参列表可能过于相似,编译器无法解决歧义。 若要解决此错误,请显式强制转换一个或多个实参。

示例

以下示例生成 C2666:

// C2666.cpp
struct complex {
   complex(double);
};

void h(int,complex);
void h(double, double);

int main() {
   h(3,4);   // C2666
}

此错误还可能来自于为 Visual Studio 2019 版本 16.1 执行的编译器一致性工作:

  • 如果一个转换提升其基础类型固定到其基础类型的枚举,另一个转换提升到已提升的基础类型(两种类型不同),那么前一个转换比后一个好。

下面的示例演示了如何在 Visual Studio 2019 16.1 及更高版本中更改编译器行为:

#include <type_traits>

enum E : unsigned char { e };

int f(unsigned int)
{
    return 1;
}

int f(unsigned char)
{
    return 2;
}

struct A {};
struct B : public A {};

int f(unsigned int, const B&)
{
    return 3;
}

int f(unsigned char, const A&)
{
    return 4;
}

int main()
{
    // Calls f(unsigned char) in 16.1 and later. Called f(unsigned int) in earlier versions.
    // The conversion from 'E' to the fixed underlying type 'unsigned char' is better than the
    // conversion from 'E' to the promoted type 'unsigned int'.
    f(e);
  
    // Error C2666. This call is ambiguous, but previously called f(unsigned int, const B&). 
    f(e, B{});
}

此错误还可能来自于为 Visual Studio .NET 2003 执行的编译器一致性工作:

  • 二进制运算符和用户定义的指针类型转换

  • 资格转换与标识转换不同

对于二元运算符 <、>、<= 和 >=,如果传递的参数的类型定义用户定义的转换运算符以转换为操作数的类型,则该参数现在被隐式转换为操作数的类型。 现在可能存在歧义。

对于在 Visual Studio .NET 2003 和 Visual Studio .NET 版本的 Visual C++ 中均有效的代码,请使用函数语法显式调用类运算符。

// C2666b.cpp
#include <string.h>
#include <stdio.h>

struct T
{
    T( const T& copy )
    {
        m_str = copy.m_str;
    }

    T( const char* str )
    {
        int iSize = (strlen( str )+ 1);
        m_str = new char[ iSize ];
        if (m_str)
            strcpy_s( m_str, iSize, str );
    }

    bool operator<( const T& RHS )
    {
        return m_str < RHS.m_str;
    }

    operator char*() const
    {
        return m_str;
    }

    char* m_str;
};

int main()
{
    T str1( "ABCD" );
    const char* str2 = "DEFG";

    // Error - Ambiguous call to operator<()
    // Trying to convert str1 to char* and then call
    // operator<( const char*, const char* )?
    //  OR
    // trying to convert str2 to T and then call
    // T::operator<( const T& )?

    if( str1 < str2 )   // C2666

    if ( str1.operator < ( str2 ) )   // Treat str2 as type T
        printf_s("str1.operator < ( str2 )\n");

    if ( str1.operator char*() < str2 )   // Treat str1 as type char*
        printf_s("str1.operator char*() < str2\n");
}

以下示例生成 C2666

// C2666c.cpp
// compile with: /c

enum E
{
    E_A,   E_B
};

class A
{
    int h(const E e) const {return 0; }
    int h(const int i) { return 1; }
    // Uncomment the following line to resolve.
    // int h(const E e) { return 0; }

    void Test()
    {
        h(E_A);   // C2666
        h((const int) E_A);
        h((int) E_A);
    }
};