如何在编译时确定平台是小端还是大端?我已经看到了使用强制转换在运行时确定的许多方法,以及一些与平台相关的选项。有便携式或标准的方法可以做到这一点吗?

constexpr bool is_little_endian = ?;

最佳答案

C++ 20将 std::endian 添加到可以在constexpr上下文中使用的<type_traits>中。

Live example of below code:

if constexpr (std::endian::native == std::endian::little) {
    std::cout << "litle endian\n";
} else if constexpr(std::endian::native == std::endian::big) {
    std::cout << "big endian\n";
} else {
    std::cout << "something silly\n";
}

10-07 12:14
查看更多