【问题标题】:Why does decltype(*this) not return the correct type?为什么 decltype(*this) 不返回正确的类型?
【发布时间】:2013-02-14 12:46:32
【问题描述】:

以下代码是使用 VC++ Nov 2012 CTP 编译的。但是编译器给出了警告。

我只是想知道这是否是 VC++ Nov 2012 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(); 
}

【问题讨论】:

  • 除非你真的做的不仅仅是在常量 Get 中返回一个值,否则你可以在非常量 Get 函数中做同样的事情。我实际上没有看到非常量 Get 的原因。
  • 示例代码仅用于概念验证。 Get() 的真正作用在这里毫无意义。
  • a 不是已经是 const 了吗?为什么它甚至会警告非 const Get 函数?
  • @Shahbaz,这是我的错,已经修复。

标签: c++ c++11 compiler-errors overloading decltype


【解决方案1】:

decltype 应用于不是 id 表达式的表达式会为您提供参考,因此 decltype(*this) 已经是 A&amp;,您不能再次使用 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&lt;A const &amp;&gt;(*this)要简单得多。

【讨论】:

  • 所以,总而言之,警告是有效的。
  • @LightnessRacesinOrbit:我很惊讶这实际上不是一个错误
  • 我并不感到惊讶。 int foo() { return foo(); } int main() { foo(); } 也不会出错,(或者是吗?!)即使它是一个等效程序。
  • 有趣的叮当声(至少在我的 Apple 上)没有发出任何警告(但确实会递归到 never-never-land。)
  • @LightnessRacesinOrbit,我误读了这个答案。我删除了之前的评论。
猜你喜欢
  • 2014-10-08
  • 2013-11-30
  • 2023-03-04
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多