函数调用歧义(用户定义的转换和 Derived2Base 指针转换)
Function call ambiguity (user-defined conversion and Derived2Base pointer conversion)
下面代码中函数调用歧义的原因是什么?
我知道这里有两个可行的函数,正如编译器在ERROR
消息中所说的那样(如下所示在末尾(
1(candidate: operator==(Base*, Base*)
-> 需要用户定义的第一个参数从SmartPtr
到Base*
的转换
-> 需要Derived*
才能Base*
隐式 (?( 转换
2(candidate: bool operator==(const SmartPtr&, const Base*)
-> 需要为第一个参数添加顶级常量(完全匹配(
-> 需要Derived*
才能Base*
隐式 (?( 转换
从上面可以清楚地看出,SmartPtr
内部定义的operator==
是更好的匹配(考虑到第一个参数和第二个参数是相同的(
代码:
#include <iostream>
using namespace std;
template<class T> class SmartPtr
{
public:
operator T*() { return pointee__;}
inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
return lhs.pointee__ == rhs;
}
private:
T* pointee__;
};
struct Base{};
class Derived:public Base{};
int main()
{
SmartPtr<Base> sp;
Derived * dp;
cout<<"Hello World"<< (sp==dp);
return 0;
}
错误:
main.cpp: In function ‘int main()’:
main.cpp:38:30: error: ambiguous overload for ‘operator==’ (operand types are ‘SmartPtr’ and ‘Derived*’)
cout<<"Hello World"<< (sp==dp);
~~^~~~
main.cpp:38:30: note: candidate: operator==(Base*, Base*)
main.cpp:19:24: note: candidate: bool operator==(const SmartPtr&, const Base*)
inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
^~~~~~~~
谢谢!
从上面很明显,在 SmartPtr 中定义的运算符 == 是更好的匹配(考虑到第一个参数(
不完全是:第一个转换为SmartPtr &
转换为SmartPtr const &
第二个需要两个转换:
1( 从Derived *
到Base *
2(从Base *
到Base const *
如果定义
Derived * dp;
指向const
的指针
Derived const * dp;
歧义消失,代码编译。
如果定义sp
const
,则相同
SmartPtr<Base> const sp{};
如果修改SmartPtr
内部的operator==()
以接受Base *
(而不是Base const *
(作为第二个参数,也会消失。
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 函数调用歧义(用户定义的转换和 Derived2Base 指针转换)