Why decltype (* this) does not return the correct type?

The following code was compiled with VC ++ Nov 2012 CTP. But the compiler gave a warning.

I just wonder if this is a VC ++ Nov 2012 CTP error.

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(); } 
+8
c ++ overloading c ++ 11 compiler-errors decltype
source share
1 answer

decltype is applied to an expression that is not an id; it gives you a link, so decltype(*this) already A& , and you cannot do it const again. If you really wanted to use decltype , you could do something like this:

 static_cast<std::decay<decltype(*this)>::type const &>(*this) 

Or even this:

 static_cast<std::add_lvalue_reference< std::add_const< std::decay<decltype(*this)>::type >::type >::type >(*this) 

Of course, it's much easier to say static_cast<A const &>(*this) .

+17
source share

All Articles