Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting vector<int> to vector<long> when they are the same size?

I have a function taking a reference to a vector of longs

Void blarf(std::vector<long>&);

This is given and shouldn't be modified. Deep into xyz.cpp is an attempt to feed blarf() a vector of ints:

std::vector<int>  gooddata;
. . . 
blarf(gooddata);

In my case and all cases for this software, int and long are the same size. Of course I can't change the definition of gooddata either.

What kind of typecast is appropriate here? I tried dynamic_cast but that's only for polymorphic class conversion. static_cast no worky either. I'm no genius at c++ type casts.

like image 410
DarenW Avatar asked Mar 01 '26 08:03

DarenW


1 Answers

No, you can't. int and long will stay different types, this would break strict aliasing rules.

You can create a vector<long> from your vector<int> very easily:

std::vector<int> vec{5, 3, 7, 9};
std::vector<long> veclong(begin(vec), end(vec));

This will copy vec into veclong, with the constructor of vector that takes two iterators.

If you want to do it the bad way (i.e. that exhibits undefined behavior), then feel free to use:

*reinterpret_cast<std::vector<long>*>(&vec)
like image 50
Asu Avatar answered Mar 02 '26 22:03

Asu