簡體   English   中英

編譯器警告“有效C ++”方法,以避免const和非const成員函數重復

[英]Compiler warning on “Effective C++”s method to avoid duplication in const and non-const member functions

該問題已更新。 請檢查代碼。

以下代碼是使用VC ++ 2012年11月CTP編譯的。 斯科特·邁耶斯(Scott Meyers)的著作《 有效的C ++ 》建議,我們應使用避免在const和非const成員函數中重復的方法。 但是,以下代碼會引發警告(級別1)。 由於WDK構建工具將警告視為錯誤,因此以下代碼無法成功編譯。

還有其他更好的方法嗎?

struct A
{
    int n;

    A(int n)
        : n(n)
    {}

    int Get() const
    {
        return n;
    }

    int Get()
    {
        return static_cast<const decltype(*this)&>(*this).Get();
    }
};

int main()
{
    const A a(8);

    //
    // warning C4717: 'A::Get' : recursive on all control paths,
    // function will cause runtime stack overflow
    //
    a.Get(); 
}

您已經轉換了兩個Get方法的主體,因此編譯器是正確的。 const Get方法正在調用自身。 您現在不高興您的構建工具將警告視為錯誤嗎? :)

交換它們:

int& Get()
{
    return const_cast<int&>(static_cast<const A&>(*this).Get());
}

const int& Get() const
{
    return n;
}

我相信你會逆轉。 這是非const版本,將constness拋棄在const版本上。

請參閱: 優雅的解決方案,以復制,const和非const,吸氣劑?

回答更新的問題。 (您應該使這個問題成為新問題)

static_cast<const decltype(*this)&>(*this)*this是類型A的左值,因此,由decltype(*this)表示的類型為A& (請參見7.1.6.2 [dcl.type.simple] / 4)。

結果,您的非常量Get()函數等效於:

int Get()
{
    typedef A & Aref;
    // IMHO a const_cast would be the better choice here
    return static_cast<const Aref&>(*this).Get();
}

引用類型上的cv限定詞將被忽略。 通過引用折疊,您的類型轉換最終等於static_cast<A&>(*this) ,因此您無需添加所需的const。

因此,在此處無法使用decl_type 如果您非常想使用它,則需要:

int Get()
{
    // Made my suggested change of cast here
    return const_cast<const std::remove_reference<decltype(*this)>::type&>(*this).Get();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM