Title.
I am implementing this class:
#include <span>
#include <vector>
class MyClass {
public:
std::span<int *> numbers(void) {
return m_numbers;
}
std::span<const int *> cnumbers(void) const {
// What to do here?
}
private:
std::vector<int *> m_numbers;
};
My first attempt was to use the automatic conversion exhibited in the non-const function (I believe this has something to do with std:decay
? I don't really understand it).
return m_numbers
This fails to compile, with no known conversion.
One implementation I've found is this:
return std::span(m_numbers.begin(), m_numbers.end());
this returns a std::span<int * const>
though, which is not exactly what I want. Variations of this using cbegin
do not seem to help.
I'm targeting c++20
You're trying to break const-correctness. Returning std::span<const int *>
would've allowed modification of those elements (pointers themselves, which won't be const
).
The correct return type should be std::span<const int * const>
, note the additional const
at the right.