为什么decltype(* this)不返回正确的类型? [英] Why does decltype(*this) not return the correct type?
本文介绍了为什么decltype(* this)不返回正确的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码是使用VC ++ 2012年11月CTP编译的。但是编译器给出了警告。
The following code was compiled with VC++ Nov 2012 CTP. But the compiler gave a warning.
我只是想知道这是VC ++ 2012年11月CTP的错误。
I just wonder whether this is a bug of VC++ Nov 2012 CTP.
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();
}
推荐答案
应用于不是id表达式的表达式的decltype 为您提供引用,因此
decltype(* this)
已经是 A&
,并且您不能再使 const
。如果你真的想使用 decltype
,你可以这样做:
decltype
applied to an expression that's not an id-expression gives you a reference, so decltype(*this)
is already A&
, and you can't make that const
again. If you really wanted to use decltype
, you could do something like this:
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)
。
这篇关于为什么decltype(* this)不返回正确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文