代码之家  ›  专栏  ›  技术社区  ›  John

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

  •  1
  • John  · 技术社区  · 6 月前

    如何在不首先编写成员varable的情况下使用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;
    }
    
    3 回复  |  直到 6 月前
        1
  •  1
  •   user12002570    6 月前

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

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

    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;
    };
    
        2
  •  1
  •   Pepijn Kramer    6 月前

    在C++11中,我会这样做;

    #include <vector>
    #include <type_traits>
    
    class Demo
    {
    using my_collection_t = std::vector<int>;
    
    public:
        my_collection_t foo() 
        {
            return m_data;
        };
    private:
         my_collection_t  m_data;
    };
    
    int main() {
        // Your main code goes here
        Demo demo;
        auto data = demo.foo();
        return 0;
    }
    

    但我更倾向于更新我的语言版本

        3
  •  0
  •   SomeWittyUsername    6 月前

    我认为在方法之前定义属性没有问题。 也就是说,可以说,在私有部分之前定义公共部分是一种更好的做法,因为它有助于类的可读性。

    在您的代码片段中,使用auto而不是使用的目的是什么 std::vector<int> 直接或通过 using ? 如果要概括不同类型的用法,那么模板是更好的候选者——将该类型作为模板参数,并在内部各处使用它,而不是通过 decltype .