问题描述
我试图通过使用统一的初始化语法强制在return语句中进行显式转换,如下所示:
I tried to force explicit conversion in return statement by means of using of uniform initialization syntax as it is in following:
#include <iostream>
#include <cstdlib>
struct A
{
explicit
operator bool () const
{
return false;
}
};
bool
f()
{
return {A{}}; // error: no viable conversion from 'void' to 'bool'
// equivalent to return bool{A{}}; at my mind
}
bool
g()
{
return static_cast< bool >(A{});
}
struct B
{
B(A) { ; }
};
B
h()
{
return {A{}};
// equivalent to return B{A{}};
}
inline
std::ostream &
operator << (std::ostream & _out, B const &)
{
return _out << "B";
}
int
main()
{
std::cout << std::boolalpha << f() << std::endl;
std::cout << std::boolalpha << g() << std::endl;
std::cout << h() << std::endl;
return EXIT_SUCCESS;
}
但是出现错误,因为它指向将代码行注释为注释。
But got an error, as it pointed against correspoinding line of code into comment.
为什么 {A {}}
的推导类型是 void
? return {/ * something * /};
的一般含义是什么?
Why deduced type of {A{}}
is void
? What is the meaning of return {/* something */};
in general? How it differs from obvious uniform initialization during simple initialization?
使用的编译器是 clang 3.6.0 。
推荐答案
进行用户定义的转换显式
时,您必须明确声明所需内容。
When you make the user-defined conversion explicit
, you are forced to explicitly state what you want.
删除显式,它可以正常工作:
Remove the explicit and it works fine:
struct A
{
operator bool () const
{
return false;
}
operator bool ()
{
return true;
}
};
bool
f()
{
return A{}; // conversion from A to bool
return {A{}}; // conversion from braced-init list to bool
}
编辑::我将尝试解决您的合理问题:
I'll try to work out your reasonable questions:
使用 bool {A {}};
您应用 ,然后返回结果(一般情况下,这意味着移动,复制或RVO)。但是由于没有从 A {}
到 bool
的隐式转换,所以它失败了。为什么?由于显式转换运算符仅参与直接初始化或显式强制转换,请参见第(2)点。
With bool{A{}};
you apply direct-list-initialization and then return the result (which in the general case implies a move, a copy or RVO). But as there is no implicit conversion from A{}
to bool
, it fails. Why? Because an explicit conversion operator only participates in direct-initialization or explicit casts, see point (2) here.
第二种情况,您返回 {A {}}
相似,但是您首先构造init-list,然后将其传递给copy-list-initialize bool返回值。因此,与 bool {A {}};
出现者中的问题相同。
The second case where you return {A{}}
is similar, but you first construct the init-list and then pass it to copy-list-initialize the bool return value. So the same problem as in bool{A{}};
occurrs.
编辑:原因在于是涉及的 void
,请参阅@PiotrS的评论。
for the reason why there is a void
involved, see the comments by @PiotrS.
这篇关于return语句中的统一初始化和显式转换运算符为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!