![](/img/trans.png)
[英]Friend function template with automatic return type deduction cannot access a private member
[英]Return type deduction with a private member variable
正如昨天的問答中所解釋的那樣 ,g ++ 4.8和Clang 3.3都正確地抱怨下面的代碼,並且在這個范圍內未聲明“'b_'未聲明”
#include <iostream>
class Test
{
public:
Test(): b_(0) {}
auto foo() const -> decltype(b_) // just leave out the -> decltype(b_) works with c++1y
{
return b_;
}
private:
int b_;
};
int main()
{
Test t;
std::cout << t.foo();
}
將private
部分移動到類定義的頂部可消除錯誤並打印0。
我的問題是, 這個錯誤在C ++ 14中是否會隨着返回類型推斷而消失 ,因此我可以省略decltype
並在類定義的末尾使用我的private
部分?
注意 :它實際上是基於@JesseGood的答案。
不,但不再需要這個,因為你可以說
decltype(auto) foo() const {
return b_;
}
這將從其正文中自動推斷出返回類型。
我不這么認為,因為C ++ 14會有自動返回類型扣除。 下面通過傳遞-std=c++1y
標志來編譯g ++ 4.8。
auto foo() const
{
return b_;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.