关于"Effective C++"方法的编译器警告,以避免const和非const成员函数中的重复

xml*_*lmx 1 c++ overloading compiler-errors const c++11

这个问题已经更新.请查看代码.

以下代码是使用VC++ 2012年11月CTP编译的.Scott Meyers的书" Effective 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(); 
}
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 6

你已经转换了两种Get方法的主体,所以编译器是正确的; const Get方法调用自身.现在您的构建工具将警告视为错误,您不高兴吗?:)

将它们交换成圆形:

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

const int& Get() const
{
    return n;
}
Run Code Online (Sandbox Code Playgroud)