【发布时间】:2014-02-04 08:15:05
【问题描述】:
我有以下示例(使用过于安全的布尔类型):
#include <cstdlib>
struct boolean_type
{
explicit
boolean_type(bool _value)
: value_(_value)
{ ; }
explicit
operator bool () const
{
return value_;
}
private :
bool value_;
};
struct A
{
A(int const _i)
: i_(_i)
{ ; }
boolean_type operator == (A const & _other) const
{
return (i_ == _other.i_);
}
private :
int i_;
};
bool t()
{
return A(0) == A(0);
}
int main()
{
return EXIT_SUCCESS;
}
众所周知,这样的代码包含错误:“could not convert '(((int)((const A*)this)->A::i_) == ((int)other .A::i))' 在bool A::operator == (A const &) const 的返回语句中从 'bool' 到 'boolean_type' 和在 bool t() 的返回语句中“无法将 'boolean_type' 转换为 'bool'”。但这里有什么风险?为什么在这两种情况下都没有显式转换?为什么是隐式的?事实上,我们在第二种情况下明确指定了返回类型 bool 和 static_assert(std::is_same< bool, decltype(std::declval< int >() == std::declval< int >()) >::value, "!"); 一样!
另外想说:
由于指定的障碍,我不能简单地将bool 的所有条目替换为我的用户代码中的超级安全boolean_type(即 mocked-object),因为,比如说,在boost::variant::operator == 的返回语句中使用上述构造,将那里视为隐式转换。类似的障碍不是唯一的。
【问题讨论】:
-
Q中根本没有重复,因为讨论中隐含着对重要细节的考虑。
-
这段代码是从哪里来的?
-
委员会对这个问题进行了很多辩论(应该返回意味着显式转换为返回类型)...
-
@Dukales 我记得那些不是公开对话。但您可以搜索 wg21 问题列表和 isocpp.org 邮件列表。
-
@JohnDibling
return是一个非常特殊的情况。您已经拼出了要转换为上面几行的类型。这与转换为函数中从未提及的某些随机类型不同。然后它变成了一个品味问题。我认为必须在每个 return 语句中重复类型是一种痛苦。
标签: c++ c++11 type-conversion implicit-conversion