在一个大项目中,我有这段代码,编译得很好,但我不明白为什么。
std::vector<std::string> foo;
if(foo == 1) // Here is the error, the good code is "if(foo.size() == 1)"
do_something();
在一个简单的测试 main 中,它无法编译。我想编译器在某处找到一个运算符并通过隐式转换使用它。
有办法知道使用的是哪一个吗?
我使用带有警告选项的 gcc 8.5.0
-Wall -Wextra -Wconversion
。
执行隐式转换的代码示例:
# include <string>
# include <vector>
# include <iostream>
class A
{
public:
A() = default;
A(A const&) = default;
A(std::vector<std::string> const& x) { std::cout << "from vector" << std::endl; }
A(int x) { std::cout << "from int" << std::endl; }
};
bool operator==(A const& a1, A const& a2) { return true; }
int main()
{
std::vector<std::string> foo = { "hello", "world", "!" };
if(foo == 1)
std::cout << "foo == 1" << std::endl;
return 0;
}
回答我自己的问题
为了找到隐式转换的来源,我创建了另一个隐式转换的来源。然后,编译器无法选择并显示可能性。
示例:
# include <string>
# include <vector>
# include <iostream>
class A
{
public:
A() = default;
A(A const&) = default;
A(std::vector<std::string> const& x) { std::cout << "A from vector" << std::endl; }
A(int x) { std::cout << "A from int" << std::endl; }
};
bool operator==(A const& a1, A const& a2) { return true; }
class B
{
public:
B() = default;
B(B const&) = default;
B(std::vector<std::string> const& x) { std::cout << "B from vector" << std::endl; }
B(int x) { std::cout << "B from int" << std::endl; }
};
bool operator==(B const& b1, B const& b2) { return true; }
int main()
{
std::vector<std::string> foo = { "hello", "world", "!" };
if(foo == 1)
std::cout << "foo == 1" << std::endl;
return 0;
}
海湾合作委员会输出:
test_vector.cpp: In function ‘int main()’:
test_vector.cpp:28:9: error: ambiguous overload for ‘operator==’ (operand types are ‘std::vector<std::__cxx11::basic_string<char> >’ and ‘int’)
if(foo == 1)
~~~~^~~~
test_vector.cpp:13:6: note: candidate: ‘bool operator==(const A&, const A&)’
bool operator==(A const& a1, A const& a2) { return true; }
^~~~~~~~
test_vector.cpp:23:6: note: candidate: ‘bool operator==(const B&, const B&)’
bool operator==(B const& b1, B const& b2) { return true; }
^~~~~~~~