Home > Mobile >  How to initialize non-const member variable with const value
How to initialize non-const member variable with const value

Time:08-08

struct IntSlice {
  int* ptr_;
  int  len_;
};

std::initializer_list<int> xs = {1, 2, 3};
const IntSlice s = {xs.begin(), (int)xs.size()}; // this does not work :(

It is giving me an error, that we cannot assign a const pointer to a non const pointer but I thought the declaration const IntSlice would fix that.

I think I know what's going on. const IntSlice is promoting int* ptr_ to int* const ptr_ not const int* const ptr_ which is what I want.

But surely, there has to be some way to promote int* ptr_ to const int* without having to create a ReadonlyIntSlice?

CodePudding user response:

IntSlice is too specific. It works only with (mutable) int slices. Why not have something that works with any type of slice?

template <typename T>
struct Slice
{
   T*          ptr_;
   std::size_t len_;
};

Now you can have Slice<int>, Slice<const int>, Slice<const * const double> and whatever else you fancy.

std::initializer_list<int> xs = {1, 2, 3};
Slice<const int> s = {xs.begin(), xs.size()};

In C 17, if you add an appropriate constructor or a deduction guide, you can omit the template argument.

template <typename T>
Slice(T* ptr, std::size_t len) -> Slice<T>;

Slice s = {xs.begin(), xs.size()};
  • Related