8

次のコードは、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(); 
}
4

1 に答える 1

17

decltypeid-expressionではない式に適用すると、参照が得られるため、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)です。

于 2013-02-28T11:00:51.433 に答える