c++ - Loss of data warning when copying to a data structure of smaller type -


i using visual studio 2013 , have code such following:

void f() {     std::vector<short> vecshort(10);     std::vector<long> veclong(10);     std::copy(veclong.begin(), veclong.end(), vecshort.begin()); } 

this gives warning:

warning c4244: '=' : conversion 'long' 'short', possible loss of data 

the trouble real code in templates. user can instantiate templates such warning occurs, logic of code prevents actual loss of data. how can suppress warning in nice way? if weren't in std::copy put cast.

edit: code used in other compilers , frowned upon me use pragmas.

i think best bet use std::transform predicate (or lambda) cast (since you're asserting no loss of data converting smaller type).

template <typename to> struct convert_to {     template<typename from>     operator()(from source) const { return static_cast<to>(source); } };  std::transform(veclong.begin(), veclong.end(), vecshort.begin(), convert_to<short>()); 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -