c++ - Compare typedef is same type -


i using c++ (not 11) , using libraries have different typedefs integer data types. there way can assert 2 typedefs same type? i've come following solution myself.. safe? thanks

template<typename t> struct typetest {     static void compare(const typetest& other) {} };  typedef unsigned long long uint64; typedef unsigned long long uint_64; typedef unsigned int uint_32;  int main() {     typetest<uint64>::compare(typetest<uint64>()); // pass     typetest<uint64>::compare(typetest<uint_64>()); // pass     typetest<uint64>::compare(typetest<uint_32>()); // fail } 

in c++11, use std::is_same<t,u>::value.

since don't have c++11, implement functionality as:

template<typename t, typename u> struct is_same  {     static const bool value = false;  };  template<typename t> struct is_same<t,t>  //specialization {     static const bool value = true;  }; 

done!

likewise can implement static_assert1 as:

template<bool> struct static_assert; template<> struct static_assert<true> {};  //specialization 

now can use them as:

static_assert<is_same<uint64,uint64>::value>(); //pass static_assert<is_same<uint64,uint32>::value>(); //fail 

or wrap in macro as:

#define static_assert(x)  { static_assert<x> static_assert_failed; (void) static_assert_failed; } 

then use as:

static_assert(is_same<uint64,uint64>::value); //pass static_assert(is_same<uint64,uint32>::value); //pass 

if use macro, see following string in compiler generated message if assert fails:

static_assert_failed 

which helpful. other information in error message, able figure out why failed.

hope helps.


1. note in c++11, static_assert operator (which operates @ compile-time), not class template. in above code, static_assert class template.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -