I have an existing C++ API function that looks like this:
void do_something(const Foo (&input_array)[N]);
I think that this takes an array of N contiguously allocated Foo structures, by reference. For example, I can pass in an array:
Foo my_array[N] = { ... }
do_something(my_array);
In my real code however I have a std::vector<Foo>
, the contents of which I understand can be treated like an array using the .data()
member function, however the following results in a compiler (clang) error:
// Say N is 2:
std::vector<Foo> my_vector(N);
// ...initialise vector values...
do_something(*my_vector.data());
It complains that there's no viable conversion from const Foo
to const Foo [2]
.
I understand that C++ considers array sizes to be considered part of the type. In this case, what would be the correct type cast? I got as far as this:
auto my_vector_as_array = static_cast<const Foo & [N]>(*my_vector.data());
However the compiler is not happy at all about the use of [N]
or even []
as part of the static cast's type parameter, complaining that:
error: 'type name' declared as array of references of type 'const Foo &'
Is there a way to correctly coerce the contents of a std::vector
into this function?
Here's the full code:
#include <iostream>
#include <vector>
#define N 4
struct Foo { int a; int b; float c; };
void do_something(const Foo (&input_array)[N]) {
for (size_t i = 0; i < N; ++i) {
std::cout << i << ": " << input_array[i].a << ", " << input_array[i].b << ", " << input_array[i].c << std::endl;
}
}
int main(int argc, char * argv[]) {
// pass a C-style array by reference:
Foo my_array[N] = { {1, 10, 100.0}, {2, 20, 200.0}, {3, 30, 300.0}, {4, 40, 400.0} };
do_something(my_array);
// try to do the same with the contents of a vector:
std::vector<Foo> my_vector(N);
my_vector[0] = {1, 10, 100.0};
my_vector[1] = {2, 20, 200.0};
my_vector[2] = {3, 30, 300.0};
my_vector[3] = {4, 40, 400.0};
// this fails to compile:
do_something(*my_vector.data());
// try casting via a temporary variable - also fails to compile:
auto my_vector_as_array = static_cast<const Foo & []>(*my_vector.data());
do_something(my_vector_as_array);
}
EDIT: it has been suggested that this is a duplicate of this question however the solutions presented there do not work in this case. I think this may be because the function defines the array reference with an explicit size, and the compiler is not happy accepting a mere pointer (because the size is lost from the type).