为什么此赋值操作会导致不明确的函数调用
Why does this assignment operation results in ambiguous function call?
考虑以下程序,它可以编译并运行良好:
#include <iostream>
#include <string>
using std::string;
struct BB
{
// generic cast
template<typename T>
operator T() const
{
std::cout<<"Generic castn";
return 0;
}
// string cast
operator string() const
{
std::cout<<"string castn";
return string("hello");
}
};
int main()
{
BB b;
string s = b; // copy constructor
}
但是如果我像下面这样稍微更改main()
函数的代码:
int main()
{
BB b;
string s;
s = b;
}
编译器给出以下错误消息(在此处查看现场演示(
[Error] ambiguous overload for 'operator=' (operand types are 'std::string {aka std::basic_string<char>}' and 'BB')
为什么这个电话是模棱两可的?这背后的原因是什么?看起来有很多超载operator=
,比如一个用于char
,一个用于char*
,一个用于const char*
等。这就是上面的程序使编译器变得模棱两可。
您的问题是您的模板转换运算符。
template<typename T>
operator T() const
{
std::cout << "Generic castn";
return 0;
}
允许将BB
转换为任何内容。 因此,可以考虑采用不同类型的std::string::operator=
的所有重载。 由于它们都是有效的,因此无法解决歧义,并且会出现错误。
如果您删除了模板转换,那么它将编译。 模板转换也可以标记为explicit
然后您可以使用所需类型的static_cast
。
你调用operator =
,但如果它是一个常规函数,那就是一样的了:
void f(int x);
void f(const string &y);
int main() {
BB b;
f(b);
return 0;
}
由于BB
可以用int
或string
转换,编译器不知道该调用哪个f
函数。
您的第一个示例工作的唯一原因是因为在那里调用了复制构造函数,并且它只将const string&
作为参数,因此没有多个选择。
相关文章:
- 父类的私有函数会导致对具有相同名称和相似参数的子类中的公共函数的不明确调用
- 对重载函数find_first_not_of的不明确调用
- 调用'Node'构造函数是不明确的
- "fpclassify":对重载函数的不明确调用
- 为什么调用具有通用或 r 值引用的重载覆盖函数是不明确的?
- 重载调用是不明确的:一对内联映射作为构造函数参数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C++具有可变参数包的函数的部分模板参数推导会在 Clang 和 MSVC 中产生不明确的调用
- 对静态重载(类)函数/方法的调用是不明确的
- 这个函数调用应该不明确吗?
- 使用列表初始化的不明确构造函数调用
- 循环依赖(类对类型定义,类型定义对类),前向声明给出不明确的调用
- 为什么初始值设定项列表中的元素数会导致不明确的调用错误
- C++中来自不同基类的不明确函数
- 对自身的不明确函数调用
- C++ 中的不明确函数
- 在c++中使用[]而不是函数调用
- 显然,不明确的调用不会在GCC上导致编译错误
- 可转换的类型和不明确的调用
- 为什么使用bind而不是函数调用?