开发者

Is there a template-meta program to determine the endianness of the compiler at compile time? [duplicate]

This question already has answers here: Closed 11 years ago.

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_endia开发者_开发百科n_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.


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.


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__
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜