Reputation: 11753
My question is related to numeric type conversion in C++. A very common way to do that is to use static_cast, for example:
float a;
int b;
a = 3.14;
b = static_cast<int>(a);
Then, how about numeric vector type conversion? Could we continue to use static_cast? I have done the following experiment:
typedef vector<int> IntVector;
typedef vector<float> FloatVector;
IntVector myvector;
myvector.push_back(3);
myvector.push_back(4);
myvector.push_back(5);
// Solution 1 (successful)
FloatVector solution1 ( myvector.begin(), myvector.end() );
for(int i=0; i<solution1.size(); i++)
cout<<solution1[i]<<endl;
// Solution 2 (failed)
FloatVector solution2;
solution2 = static_cast<FloatVector> (myvector);
It seems that for numeric vector types it is impossible to use static_cast to convert. I was wondering whether there are good solutions to this problem. Thanks!
Upvotes: 2
Views: 1243
Reputation: 145204
The language directly supports conversion from one numeric type to another. You do not even need the static_cast
, you could just assign. This conversion involves a logical copying of the value, as opposed to a reinterpretation of the value representation.
The language does not directly support conversion between arrays of different types, or for that matter of std::vector
of different types.
But as you found, there is some support for copying elements, and then when each element is numeric, the built-in support for numeric type conversion kicks in for each element.
Upvotes: 2
Reputation: 105876
You can neither assign nor cast a container with a template parameter T
(std::vector<int>
) into another with a template parameter L
(std::vector<float>
). They are different classes after all.
However, since they use iterators you can fill your FloatVector
with std::copy
:
FloatVector solution2(myvector.size());
std::copy(myvector.begin(),myvector.end(),solution2.begin());
Edit to address your comment:
If your current function signature is f(FloatVector)
I would recommend you to change it to
template< class T >
ReturnType f(std::vector<T> myVector, ....);
Upvotes: 2
Reputation: 70931
You can use std::copy, as it performs sequential assignement.
Upvotes: 3