Rostislav
Rostislav

Reputation: 3977

gsl::array_view<const gsl::cstring_view<>> from std::vector<std::string>

Assume I have a member variable std::vector<std::string> in a class and I want to return it from a member function as an immutable view using a combination of gsl::array_view and gsl::cstring_view. Unfortunately, the following doesn't compile:

class C {
public:
    gsl::array_view<const gsl::cstring_view<>> getVectorOfStrings() const 
    { 
         return _vectorOfStrings; 
    }

private:
    std::vector<std::string> _vectorOfStrings;
};

The reason for this is that there's no container of cstring_view that the array_view can be created from. So my question is: is there a way to use such a construct without explicitly adding something like a member of type std::vector<gsl::cstring_view<>>, which is clearly undesirable?

Edit

It seems to me that such 'transforming' views might be of more general use. Consider having a vector of owning pointers, such as std::vector<std::shared_ptr<T>>, which I'd like to expose to the user of the class as an array_view of raw pointers: gsl::array_view<const T*> without exposing my implementation-defined storage approach. Thoughts?

Upvotes: 2

Views: 1906

Answers (1)

MikeMB
MikeMB

Reputation: 21166

Per definition, views usually only provide references to existing objects. As a result, there is no way to create a normal array_view<const cstring_view<>> without first creating an matching container like e.g. a vector<const cstring_view<>>.

What you could do however, is to create your own specialization for gsl::array_view<const cstring_view<>>, that creates a cstring_view<> on demand (when the index operator is called and when the iterator is dereferenced). While this would save you a dynamic memory allocation and reduce the memory footprint compared to the naive approach, I don't it's worth the added complexity in most cases.

If you want to follow a generalized approach as described in your edit, you might want to have a look at boost::transform_iterator - either for direct use or as an inspiration for your own generalized transform_array_view class (which I'm sure, would be a welcome addition to the gsl or boost).

Upvotes: 1

Related Questions