Can I use const in vectors to allow adding elements, but not modifications to the already added?

后端 未结 14 616
既然无缘
既然无缘 2020-12-01 04:54

My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code:



        
14条回答
  •  暖寄归人
    2020-12-01 05:25

    Well, in C++0x you can...

    In C++03, there is a paragraph 23.1[lib.containers.requirements]/3, which says

    The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

    This is what's currently preventing you from using const int as a type argument to std::vector.

    However, in C++0x, this paragraph is missing, instead, T is required to be Destructible and additional requirements on T are specified per-expression, e.g. v = u on std::vector is only valid if T is MoveConstructible and MoveAssignable.

    If I interpret those requirements correctly, it should be possible to instantiate std::vector, you'll just be missing some of its functionality (which I guess is what you wanted). You can fill it by passing a pair of iterators to the constructor. I think emplace_back() should work as well, though I failed to find explicit requirements on T for it.

    You still won't be able to sort the vector in-place though.

提交回复
热议问题