我正在寻找一个基于 https://www.fluentcpp.com/category/strong-types/ 的包装类主要区别是我替换了 get()
具有显式转换运算符的方法,因为这会在使用时在代码审查期间引发问题。
正如您在下面的简化代码中看到的,我有 3 个强制转换运算符重载:
- 来自
const A &
至int
- 来自
A &&
至int
- 来自
const A &
至const int &
写入时:static_cast<int>(a)
,我预计 const A &
的过载至int
要使用的。然而,它似乎有利于int
和 const int &
过载同等。 为什么要这样做?
与此类似,似乎允许const int &r = static_cast<const int &>(createA());
我认为这是一个终身错误。 (假设createA按值返回A)
编译器资源管理器中的简化代码:https://gcc.godbolt.org/z/YMH9Ed
#include <utility>
struct A
{
int v = 42;
explicit operator int() const & { return v; } // Removing this line works
explicit operator int() && { return std::move(v); }
explicit operator const int &() const & { return v; }
};
int main(int, char**)
{
A a;
int r = static_cast<int>(a);
return r;
}
编译错误:
<source>:14:13: error: ambiguous conversion for static_cast from 'A' to 'int'
int r = static_cast<int>(a);
^~~~~~~~~~~~~~~~~~~
<source>:6:14: note: candidate function
explicit operator int() const & { return v; }
^
<source>:8:14: note: candidate function
explicit operator const int &() const & { return v; }
^
最佳答案
explicit operator int() const & { return v; }
和
explicit operator const int &() const & { return v; }
同样具有良好的转化效果。 a
是左值,因此可以调用这两个函数。 a
也不是 const
,因此两个函数都必须对 a
应用 const 转换,因此它们仍然同样好。剩下的就是“返回类型”,int
或 const int&
,但是它们都同样可以用来创建int
。
您需要删除其中一个转换运算符,或者删除常量 来自
explicit operator const int &() const & { return v; }
把它变成
explicit operator const int &() & { return v; }
所以非 const 左值给你一个 const 引用。
关于c++ - 当 const-ref 和 value 存在时,为什么转换运算符会导致不明确的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54161013/