Why can't I make a vector of references?

前端 未结 9 725
梦如初夏
梦如初夏 2020-11-22 03:32

When I do this:

std::vector hello;

Everything works great. However, when I make it a vector of references instead:



        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 04:21

    Ion Todirel already mentioned an answer YES using std::reference_wrapper. Since C++11 we have a mechanism to retrieve object from std::vector and remove the reference by using std::remove_reference. Below is given an example compiled using g++ and clang with option
    -std=c++11 and executed successfully.

    #include 
    #include 
    #include
    
    class MyClass {
    public:
        void func() {
            std::cout << "I am func \n";
        }
    
        MyClass(int y) : x(y) {}
    
        int getval()
        {
            return x;
        }
    
    private: 
            int x;
    };
    
    int main() {
        std::vector> vec;
    
        MyClass obj1(2);
        MyClass obj2(3);
    
        MyClass& obj_ref1 = std::ref(obj1);
        MyClass& obj_ref2 = obj2;
    
        vec.push_back(obj_ref1);
        vec.push_back(obj_ref2);
    
        for (auto obj3 : vec)
        {
            std::remove_reference::type(obj3).func();      
            std::cout << std::remove_reference::type(obj3).getval() << "\n";
        }             
    }
    

提交回复
热议问题