vector and const

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

Consider this

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

The followi

10条回答
  •  天涯浪人
    2020-12-03 07:51

    Templates are a bit strange that way. The fact that there's an implicit conversion from T to U doesn't mean that there's an implicit conversion from XXX to XXX. It can be made to happen, but it takes a fair amount of extra work in the template code to make it happen, and offhand, I doubt the techniques were all known when std::vector was being designed (more accurately, I'm pretty sure they weren't known).

    Edit: Issues like this are part of the motivation behind using iterators. Even though a container of X isn't implicitly convertible to a container of const X, a container::iterator is implicitly convertible to a container::const_iterator.

    If you replace your:

    void f(vector& p) {}
    

    with:

    template 
    void f(const_iter b, const_iter e) {}
    

    Then:

    int main() { 
        vector nonConstVec;
        f(nonConstVec.begin(), nonConstVec.end());
        return 0;
    }
    

    will be just fine -- and so will:

    vector constVec;
    f(constVec.begin(), constVec.end());
    

提交回复
热议问题