c++c++11decltype

How to use decltype when the related data is defined later with C++11?


How to make the code snippet below compile with C++11 without writing the member varaible firstly? It looks ugly to write member variales before member functions.

#include <vector>

class Demo
{
public:
    decltype(m_data) foo(){
        return m_data;
    };
private:
    std::vector<int> m_data;
};

int main() {
    // Your main code goes here
    Demo demo;
    auto data = demo.foo();
    return 0;
}

For C++14, this code works:

#include <vector>

class Demo {
public:
    decltype(auto) foo();
private:
    std::vector<int> m_data;
};

decltype(auto) Demo::foo() {
    return m_data;
}

int main() {
    Demo demo;
    auto data = demo.foo();
    // Your main code goes here
    return 0;
}

Solution

  • It looks ugly to write member variables before member functions

    If you don't want to write member variables before than you can provide typedefs etc before member functions as shown below:

    class Demo
    {
    private:
       //provide all typedefs/aliases here 
       using vec_t = std::vector<int>;
    public:
    //---vvvv--------->use typedef name
         vec_t foo()
         {
            return m_data;
         }
    private:
        
        vec_t m_data;
    };