后续用C++11定义相关数据时如何使用decltype?

问题描述 投票:0回答:1

如何在不先写成员变量的情况下让下面的代码片段用C++11编译?在成员函数之前写成员变量看起来很难看

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

对于 C++14,此代码有效:

#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;
}
c++ c++11
1个回答
0
投票

成员变量写在成员函数之前看起来很丑

如果您不想在之前编写成员变量,可以在成员函数之前提供 typedef 等,如下所示:

class Demo
{
private:
   //provide all typedefs/aliases here 
   using type = std::vector<int>;
public:
//---vvvv--------->use typedef name
     type foo()
     {
        return m_data;
     }
private:
    
    type m_data;
};
© www.soinside.com 2019 - 2024. All rights reserved.