Enabling implicit conversion from `vector<const T>&` to `const vector<T>&`

Viewed 129

Suppose we define a class template<typename T> class vector that behaves like std::vector except that we are able to alter its class definition.

Suppose also that we have a function f(const vector<T>&).

How can we enable an implicit conversion that would allow us to pass a vector<const T>& into f?


I think such an implicit conversion is sensible, because I believe the restrictions imposed by the const vector<T>& are a superset of the restrictions imposed by the vector<const T>&. But any guidance that might be enlightening would be appreciated.

1 Answers

Supposing that f is indeed a function for some concrete T, as opposed to a function template (i.e. template<typename T> f(vector<T> const&)), then the following operator inside of vector<T> should work:

template<typename U = T, typename = std::enable_if_t<std::is_const<U>{}>>
operator vector<std::remove_const_t<U>>() const {
    // ...
}

Online Demo

However, f cannot be a standalone function template as its T will simply be deduced to be itself const and no conversion will take place. Overloading can solve this, but will be ugly.

N.b. this is presumably just making a copy of the elements inside of the original vector; returning a vector<T> const& that somehow aliases the internals of the original vector<T const> is a significantly different task, as it would involve extra lifetime-management state and/or questionably-legal type aliasing.

Related