templates - C++: Conversion from T to unsigned T -
we excessively use templates , cannot tell signedness of type @ hand, need techniques hide warnings optimized out. have simple assert(condition) macro throws if condition not evalutes true.
the goal check range of t typed count value. need @ least zero, @ max of size_t.
template<typename someintegral> someintegral zero() { return someintegral(0); } template<typename t> class c { public: void f(t count) { std::vector<std::string> ret; assert(count>=zero<t>()); // check #1 assert(count<std::numeric_limits<size_t>::max()); // check #2 ret.reserve(size_t(count)); // needs check #1 , #2 succeed. // ... } // ... }; the #1 check compiles without warning, #2 check says comparison between signed , unsigned integer expressions, because in particular case count has signed type. if assert((unsigned t) count < std::numeric_limits<size_t>::max()) or similar somehow... converting unsigned t safe in situation, because know check #1 @ least zero.
... or other compiler agnostic approach can use?
i think can use std::make_signed or std::make_unsigned. whichever fits need.
here custom implementation.
namespace internal { #define mk_makesigned(t,v) \ template<> struct make_signed<t> { \ public: \ typedef v type; \ }; template<typename t> struct make_signed { typedef t type; }; mk_makesigned(unsigned int, signed int); mk_makesigned(unsigned char, signed char); // .... can convert anything. #undef mk_makesigned }; internal::make_signed<unsigned char>::type c;
Comments
Post a Comment