简体   繁体   English

重载强制转换运算符时的C ++模糊性

[英]C++ ambiguity while overloading cast operator

Found: 实测:
Ambiguity while overloading the cast operator 重载演员运算符时的歧义

and

C++ Operator Ambiguity C ++运算符歧义

not helpful 没有帮助

Situation: 情况:

Inside the container class's body I have: 在容器类的主体内部,我具有:

operator T& () const {
    return *data;
}

operator const T& () const {
    return *data;
}

The intent being that: 目的是:

container<object> test = new object;
object& whatever = test; //<--uses (T&) cast
const object& other = test; //<--uses (const T&) cast

However the second one causes an error because it is ambiguous. 但是,第二个错误是因为模棱两可而引起的。

I completely see why the compiler is complaining, it is okay to assign a object& and a const object& to a const object& however I'd like it to not complain and choose the second (return const object& ) 我完全明白为什么编译器是抱怨,它是好的分配一个object&const object&一个const object&不过我想它不会抱怨,选择第二(返回const object&

Oh wait, just got my answer. 哦,等等,得到我的答复。

Even though they're different conversion operators (not just overloads of one), the ambiguity is resolved by removing the const you have on the first one. 即使它们是不同的转换运算符(不仅仅是一个运算符的重载),也可以通过删除第一个运算符上的const来解决歧义。

Thus: 从而:

operator T& () {
    return *data;
}

operator const T& () const {
    return *data;
}

Alternatively, if it really makes sense to provide non- const access to the pointed to data via a const object, then just do 或者,如果通过const对象提供对指向数据的非const访问确实有意义,则只需执行

operator T& () const {
    return *data;
}

Stop being silly. 别傻了 As I said you may assign a object& or a const object& to a const object& so the first cast operator is sufficient for the job in either case. 就像我说的,你可以分配object&const object&一个const object&所以第一投运营商是足以在任何情况下工作。

Silly me. 傻我 Hope this helps someone in the future! 希望这对以后的人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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