0

Here's my situation:

I'm given data as a pointer say double*.

I want to wrap this in a vector to use a library, and to avoid messing around with pointers.

Not wanting to copy the entire array, I use a vector of reference wrappers. If I then want to get the double* back from said vector after using the library, can I get this by casting the vector.data() function?

For example:

double* arr = new double[10];
vector<reference_wrapper<const double> > vec(arr,arr+10);

//use library in some manner.

//is this allowed? is there a more appropriate way?
//or should I forget using reference_wrappers in this way.
double* res = (double*) vec.data()
Niall
  • 30,036
  • 10
  • 99
  • 142
retrocookie
  • 319
  • 2
  • 10
  • 1
    A `std::reference_wrapper*` is *not* a `T*`. No amount of casting is going to change that. – WhozCraig Jul 29 '14 at 13:45
  • 1
    This vector of reference wrappers looks doesn't buy you much. You are better off not afraiding to "mess around with pointers". If you don't have to manage lifetime of pointed-to objects, then *pointers are iterators*, no more and no less. – n. m. could be an AI Jul 29 '14 at 13:52

2 Answers2

3

No, it is not possible.

double and reference_wrapper<const double> are completely unrelated types, there is no way to do this cast.

If you really need to manipulate C-style arrays, you should stick with std::vector<double>, and access the underlying array with the data() member function when needed.

quantdev
  • 23,517
  • 5
  • 55
  • 88
  • I thought the library would require an `std::vector` as input, not `std::vector` – CK1 Jul 29 '14 at 14:03
  • OK. The answer is the same without const right? I guess I'll have to copy the array. – retrocookie Jul 29 '14 at 14:11
  • @retrocookie yes it is – quantdev Jul 29 '14 at 14:12
  • Strictly speaking, it's not true to say reference_wrapper isn't related to double. It defines operator const double&(); Therefore there is a valid deterministic path to converting one to a double*: double* res3 = &const_cast(static_cast(vec[0])); – Brandon Kohn Jul 29 '14 at 14:29
0

No, you can't do that.

You can do this (but it's ugly):

double* arr = new double[10];
std::vector<std::reference_wrapper<double>> vec(arr, arr + 10);

//use library in some manner.

//is this allowed? is there a more appropriate way?
//or should I forget using reference_wrappers in this way.
double* res = &vec[0].operator double &();
assert(res == arr);

I would forget using reference_wrapper like this and instead look at boost range:

http://www.boost.org/doc/libs/1_55_0/libs/range/doc/html/range/reference/utilities/iterator_range.html

Brandon Kohn
  • 1,612
  • 8
  • 18