【发布时间】:2017-03-29 05:42:06
【问题描述】:
有没有办法禁用转换运算符?将它们标记为“= delete”会搞砸其他事情。
考虑以下代码:
class Foo
{
public:
Foo() :mValue(0) {}
~Foo() = default;
Foo(int64_t v) { mValue = v; }
Foo(const Foo& src) = default;
bool operator==(const Foo& rhs) { return mValue == rhs.mValue; }
/* after commenting these lines the code will compile */
operator int() const = delete;
operator int64_t() const = delete;
private:
int64_t mValue;
};
int main()
{
Foo foo1(5);
Foo foo2(10);
bool b1 = (foo1 == foo2);
bool b2 = (foo1 == 5);
}
这不会编译,因为 gcc 抱怨 == 运算符不明确:
test.cc: In function ‘int main()’:
test.cc:25:21: error: ambiguous overload for ‘operator==’ (operand types are ‘Foo’ and ‘int’)
bool b2 = (foo1 == 5);
^
test.cc:25:21: note: candidates are:
test.cc:25:21: note: operator==(int, int) <built-in>
test.cc:25:21: note: operator==(int64_t {aka long int}, int) <built-in>
test.cc:10:10: note: bool Foo::operator==(const Foo&)
bool operator==(const Foo& rhs) { return mValue == rhs.mValue; }
^
但是,在注释转换运算符后,代码将很好地编译和运行。
第一个问题是:为什么删除的转换运算符会给 == 运算符造成歧义?我认为他们应该禁用隐式 Foo -> int 转换,但它们似乎会影响 int -> Foo 转换,这对我来说听起来不合逻辑。
第二个:有没有办法将转换运算符标记为已删除?是的,通过不声明它们 - 但我正在寻找一种方法,以便将来任何人都可以看到这些转换被设计禁用。
【问题讨论】:
-
抛开其他人提到的解决问题,看起来你正试图让
operator==通过Foo分发给它的成员,你使用foo1 == 5应该意味着值是可与由值构造的 Foo 互换。像这样:template<class S> bool operator==(S && s) const { return *this == Foo(forward<S>(s)); }代表operator==(Foo const&)给定Foo::Foo(S &&)。有什么想法吗?
标签: c++ operators implicit-conversion deleted-functions