【问题标题】:Is there a template-meta program to determine the endianness of the compiler at compile time? [duplicate]是否有一个模板元程序可以在编译时确定编译器的字节顺序? [复制]
【发布时间】:2011-06-01 01:43:22
【问题描述】:

可能重复:
Is there a way to do a C++ style compile-time assertion to determine machine's endianness?

我正在寻找一个本着 Boost::type_traits 精神的模板元程序,它会返回编译器是大端还是小端。类似于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 标头可以跨平台获取它。

标签: c++ c boost


【解决方案1】:

有一个 Boost 头文件定义了一个可以使用的宏:boost/detail/endian.hpp。无需求助于模板元编程。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 2012-04-12
      相关资源
      最近更新 更多