c++ - bool and sizeof conditional template -
i'm testing struct i'm trying use template conditions, i'm having strange compiler errors. here code:
#include <type_traits> #include <string> template<typename t1, typename t2, bool same_size = (sizeof(t1)==sizeof(t2))> struct same_size { typedef typename std::false_type value; }; template<typename t1, typename t2> struct same_size<t1, t2, true> { typedef typename std::true_type value; }; int main() { if(same_size<char,unsigned char>::value) { printf("yes"); } system("pause"); } i'm compiling in visual studio 2015. these compiler errors get:
1> main.cpp 1>c:\users\luis\documents\visual studio 2015\projects\stringtype\stringtype\main.cpp(18): error c2059: syntax error: ')' 1>c:\users\luis\documents\visual studio 2015\projects\stringtype\stringtype\main.cpp(19): error c2143: syntax error: missing ';' before '{' can shed light going on here?
you having value type, not value. can't use in if condition. best thing can use inheritance , save on typing. so:
#include <type_traits> #include <string> template<typename t1, typename t2, bool same_size = (sizeof(t1)==sizeof(t2))> struct same_size : std::false_type { }; template<typename t1, typename t2> struct same_size<t1, t2, true> : std::true_type { }; int main() { if(same_size<char,unsigned char>::value) { printf("yes"); } system("pause"); } another (better in view) solution suggested @gmannickg:
template<typename t1, typename t2> struct same_size : std::integral_constant<bool, sizeof(t1) == sizeof(t2)> {}; the benefits of above are, of course, less typing , less error prone: in first solution, still write same_size<int, int, false>::value , wrong results.
and beauty of second solution still going produce types compatible true_type , false_type, latter typedefs corresponding integral_constant.
on side note, seeing template metaprogramming , printf in same code seeing space shuttle drawn pair of horses.
Comments
Post a Comment