考虑以下代码:
#include <iostream>
class first
{
public:
constexpr first(bool val) noexcept : _value{val} {}
constexpr operator bool() const noexcept {return _value;}
private:
bool _value;
};
class second
{
public:
constexpr second(first val) noexcept : _value{val} {}
constexpr operator first() const noexcept {return _value;}
private:
first _value;
};
int main(int argc, char** argv)
{
first f{false};
second s{true};
bool b1 = f;
bool b2 = s; // Not compiling
return 0;
}
直到最近,我还认为标准和编译器足够“聪明”,可以在需要的转换序列存在时找到它。
换句话说,我在想它bool b2 = s
会转换s
为first
,然后转换为bool
。但显然它没有发生。
获得 和 的等效行为的正确方法是first
什么second
?