为什么decltype(*this)没有返回正确的类型?

xml*_*lmx 8 c++ overloading compiler-errors decltype c++11

以下代码是使用VC++ 2012年11月CTP编译的.但编译器发出了警告.

我只是想知道这是否是VC++ 2012年11月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(); 
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 17

decltype应用于一个不是id-expression的表达式会给你一个引用,所以decltype(*this)已经存在A&,你不能再这样做const了.如果你真的想使用decltype,你可以这样做:

static_cast<std::decay<decltype(*this)>::type const &>(*this)
Run Code Online (Sandbox Code Playgroud)

甚至这个:

static_cast<std::add_lvalue_reference<
                 std::add_const<
                      std::decay<decltype(*this)>::type
                 >::type
            >::type
>(*this)
Run Code Online (Sandbox Code Playgroud)

当然,说起来要简单得多static_cast<A const &>(*this).