Soo*_*Soo 0 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;
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 11进行编译时,出现以下错误.
error: ‘value’ function with trailing return type has ‘auto&’ as its type rather than plain ‘auto’
auto& A::value()->T &
^
Run Code Online (Sandbox Code Playgroud)
等效代码(注释函数)工作正常.但是我想使用尾随返回类型.
如果要使用尾随返回类型,auto则在通常放置返回类型的位置处除了说明符之外不能有任何其他内容:
auto A::value()->T &
// ^ no '&' here
{
return m_value;
}
Run Code Online (Sandbox Code Playgroud)
你之后指定的类型->已经是一个参考,所以不用担心.