是否有一个模板元程序来确定编译器在编译时的端序

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

本文关键字:编译 编译器 有一个 程序 是否      更新时间:2023-10-16

可能重复:
有没有一种方法可以进行C++风格的编译时断言来确定machine';s endianness?

我正在寻找一个本着Boost::type_traits精神的模板元程序,它将返回编译器是big还是little endian。类似is_big_endian<T>。我该怎么写?

它的用途是创建一个库,通过实现基于端序的特定模板专门化,该库将自动适应环境。例如,

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];
}

这将允许is_big_endian作为模板参数传递。

有一个Boost头文件,它定义了一个可以使用的宏:Boost/detail/endian.hpp。不需要使用模板元编程。

如果使用gcc(或clang),则可以使用预处理器变量__BYTE_ORDER__:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
// little endian stuff
#else
// big endian stuff
#endif // __BYTE_ORDER__