Return type deduction with a private member variable

北城余情 提交于 2019-12-04 16:02:11

问题


As was explained in this Q&A yesterday, both g++ 4.8 and Clang 3.3 correctly complain about the code below with an error like "'b_' was not declared in this scope"

#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();
}

Moving the private section to the top of the class definition eliminates the error and prints 0.

My question is, will this error also go away in C++14 with return type deduction, so that I can leave out the decltype and have my private section at the end of the class definition?

NOTE: It actually works based on @JesseGood 's answer.


回答1:


No, but there not anymore is a need for this because you can say

decltype(auto) foo() const { 
    return b_;    
}

This will deduce the return type automatically from its body.




回答2:


I don't think so, because C++14 will have automatic return type deduction. The following compiles with g++ 4.8 by passing the -std=c++1y flag.

auto foo() const
{ 
    return b_;    
}    


来源:https://stackoverflow.com/questions/16800578/return-type-deduction-with-a-private-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!