尾随返回类型以供参考

时间:2017-11-28 18:45:15

标签: c++ c++11 trailing-return-type

请考虑以下代码。

#include <iostream>

class A {

public:
    using T = float;
    A(const T& x)
    {
        m_value = x;
    }

    T& value();

private:
    T m_value;
};

// A::T& A::value()
//  {
//      return m_value;
//  }

auto& A::value() -> T &
{
    return m_value;
}

int main()
{
    A a(10.0);
    std::cout << a.value() << std::endl;

    return 0;
}

使用C ++ 11编译时,出现以下错误。

error: ‘value’ function with trailing return type has ‘auto&’ as its type rather than plain ‘auto’
   auto& A::value()->T &
                       ^

等效代码(注释函数)工作正常。 但我想使用尾随返回类型。

1 个答案:

答案 0 :(得分:6)

如果要使用尾随返回类型,除了通常放置返回类型的地方的auto说明符之外,不能有任何其他内容:

auto  A::value()->T &
//  ^ no '&' here
{
    return m_value;
}

->之后指定的类型已经是参考,所以不用担心。

相关问题