0

I'm trying to create a pointer to a vector of floats that I have, so that I can pass it to a generic function that looks something like this:

foo<Type>(Type *const *, size_t)

However, as I'm somewhat new to c++, I'm having difficulties understanding how the syntax in the first parameter should be interpreted, in particular the " *const * ". What exactly would I need to put as an argument?

Any help would be appreciated!

  • 3
    Does this answer your question? [What is the difference between const int\*, const int \* const, and int const \*?](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) – cigien Apr 13 '20 at 21:46
  • You need to supply a pointer to a constant pointer to this `Type`. – Sam Varshavchik Apr 13 '20 at 21:48

1 Answers1

3

const applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right instead.

So, in Type *const *, the const applies to the 1st *. So this would mean that the parameter is a non-const pointer (the 2nd *) to a const pointer (the 1st *) to a non-const Type instance. Which would be written like this when calling foo() with a vector of floats:

vector<float> vec;
// populate vec as needed...
float* const ptr = vec.data(); // or: ... = &vec[0];
foo<float>(&ptr, vec.size());

However, depending on what foo() actually does, you probably don't need that extra level of indirection and can remove one of the pointers:

foo<Type>(const Type *, size_t);
vector<float> vec;
// populate vec as needed...
foo<float>(vec.data()/* or: &vec[0] */, vec.size());
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770