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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With