5

Possible Duplicate:
Is there a way to do a C++ style compile-time assertion to determine machine's endianness?

I am looking for a template meta program in the spirit of Boost::type_traits that would return whether the compiler is big or little endian. Something like is_big_endian<T>. How do I write this?

The use of this is to create a library that will automatically adapt itself to the environment, by implementing specific template specialization based on the endian-ness. For example,

template<>
void copy_big_endian_impl<true>(T *dst, const T *src, size_t sz) {
         // since already big endian, we just copy
         memcpy(dst, src, sz*sizeof(T));
}
template<>
void copy_big_endian_impl<false>(T *dst, const T *src, size_t sz) {
         for (int idx=0; idx<sz; idx++)
             dst[idx] = flip(src[idx];
}

This would allow is_big_endian to be passed as a template argument.

Community
  • 1
  • 1
sep
  • 3,409
  • 4
  • 29
  • 32
  • What you probably need is not metaprogramming but old fashioned macros. Architecture-specific headers often contain that sort of information, maybe there's a boost header that will have a cross-platform way of getting it though. – Seth Johnson Jun 01 '11 at 01:47

2 Answers2

4

There is a Boost header file that defines a macro you can use: boost/detail/endian.hpp. There's no need to resort to template metaprogramming.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Seth Johnson
  • 14,762
  • 6
  • 59
  • 85
3

if you're using gcc (or clang), you can use the preprocessor variable __BYTE_ORDER__:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
// little endian stuff
#else
// big endian stuff
#endif // __BYTE_ORDER__
Bobby Powers
  • 2,863
  • 23
  • 15