vector and const

后端 未结 10 1726
無奈伤痛
無奈伤痛 2020-12-03 07:13

Consider this

 void f(vector& p)
 {
 }
 int main()
 { 
  vector nonConstVec;
  f(nonConstVec);
 }

The followi

10条回答
  •  醉话见心
    2020-12-03 07:35

    Others have already given the reason why the code you gave doesn't compile, but I have a different answer on how to deal with it. I don't believe there's any way to teach the compiler how to automatically convert the two (because that would involve changing the definition of std::vector). The only way around this annoyance is to do an explicit conversion.

    Converting to a completely different vector is unsatisfying (wastes memory and cycles for something that should be completely identical). I suggest the following:

    #include 
    #include 
    
    using namespace std;
    
    typedef int T;
    
    T a = 1;
    T b = 2;
    
    void f(vector& p)
    {
        for (vector::const_iterator iter = p.begin(); iter != p.end(); ++iter) {
            cout << **iter << endl;
        }
    }
    vector& constify(vector& v)
    {
      // Compiler doesn't know how to automatically convert
      // std::vector to std::vector because the way
      // the template system works means that in theory the two may
      // be specialised differently.  This is an explicit conversion.
      return reinterpret_cast&>(v);
    }
    int main()
    {
      vector nonConstVec;
      nonConstVec.push_back(&a);
      nonConstVec.push_back(&b);
      f(constify(nonConstVec));
    }
    

    I'm using reinterpret_cast to declare that the two things are the same. You SHOULD feel dirty after using it, but if you put it in a function by itself with a comment for those following you, then have a wash and try to continue on your way with a good conscience, though you will always (rightly) have that nagging worry about someone pulling the ground out from under you.

提交回复
热议问题