Search code examples
c++c++11vectorarray-view

Interpret a std::string as a std::vector of char_type?


I have a template<typename T> function that takes a const vector<T>&. In said function, I have vectors cbegin(), cend(), size(), and operator[]. As far as I understand it, both string and vector use contiguous space, so I was wondering if I could reuse the function for both data types in an elegant manner.

Can a std::string be reinterpreted as a std::vector of (the appropriate) char_type? If so, what would the limitations be?


Solution

  • If you make your template just for type const T& and use the begin(), end(), etc, functions which both vector and string share then your code will work with both types.