Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type deduction with a private member variable

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.

like image 901
TemplateRex Avatar asked May 28 '13 20:05

TemplateRex


2 Answers

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.

like image 171
Johannes Schaub - litb Avatar answered Nov 13 '22 06:11

Johannes Schaub - litb


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_;    
}    
like image 5
Jesse Good Avatar answered Nov 13 '22 06:11

Jesse Good