下面的代码是用vc++十一月2012 CTP编译的。但是编译器给出了一个警告。
我只是想知道这是否是vc++十一月2012 CTP的一个bug。
struct A
{
int n;
A(int n)
: n(n)
{}
int Get() const
{
return n;
}
int Get()
{
//
// If using "static_cast<const A&>(*this).Get();" instead, then OK.
//
return static_cast<const decltype(*this)&>(*this).Get(); // Warning!
}
};
int main()
{
A a(8);
//
// warning C4717: 'A::Get' : recursive on all control paths,
// function will cause runtime stack overflow
//
a.Get();
}
decltype
应用于一个非id表达式,给你一个引用,所以decltype(*this)
已经是A&
了,你不能再把它变成const
了。如果你真的想使用decltype
,你可以这样做:
static_cast<std::decay<decltype(*this)>::type const &>(*this)
或者
static_cast<std::add_lvalue_reference<
std::add_const<
std::decay<decltype(*this)>::type
>::type
>::type
>(*this)
当然,直接写static_cast<A const &>(*this)
要简单得多。