如果我想在没有更新编译器的情况下使用新功能,该怎么办?

What shall I do if I want use new feature without update compiler?

本文关键字:新功能 怎么办 情况下 编译器 更新 如果      更新时间:2023-10-16

eg.我只想使用std::byte,我不需要 17 中的其他新功能。但也许将来会使用。那我现在该怎么办?

1

#if __cplusplus  < 201703L
namespace std {
enum class byte : unsigned char {};
}
#endif

阿拉伯数字

#if __cplusplus  < 201703L
namespace std {
typedef byte uint8_t;
}
#endif

或者不std命名空间中添加这些,只需使用uint8_t.

或任何其他建议...

我知道1和2非常丑陋,但对我来说是最简单的。

当您希望代码向后兼容旧C++版本时,通常会在兼容层中提供自己缺少的组件的实现。例如,创建一个byte.h标头,用于在您自己的命名空间中定义byte类型,如下所示:

#include <cstddef>
namespace my_namespace {
#if __cplusplus  < 201703L
enum class byte : unsigned char {};
#else
using std::byte;
#endif
}
std::byte

在纯C++中不能完全实现。您需要一些编译器支持才能将对象复制到std::byte[N]并从中读取,而无需 UB。

如果您只将其用于按位运算符,则可以执行如下实现:

enum class byte : unsigned char {};
template <class IntegerType>
constexpr IntegerType to_integer(byte b) noexcept { return static_cast<IntegerType>(b); }
template <class IntegerType>
constexpr byte operator <<(byte b, IntegerType shift) noexcept { return byte(static_cast<unsigned int>(b) << shift); }
template <class IntegerType>
constexpr byte operator >>(byte b, IntegerType shift) noexcept { return byte(static_cast<unsigned int>(b) >> shift); }
constexpr byte operator|(byte l, byte r) noexcept { return byte(static_cast<unsigned int>(l) | static_cast<unsigned int>(r)); }
constexpr byte operator&(byte l, byte r) noexcept { return byte(static_cast<unsigned int>(l) & static_cast<unsigned int>(r)); }
constexpr byte operator^(byte l, byte r) noexcept { return byte(static_cast<unsigned int>(l) ^ static_cast<unsigned int>(r)); }
constexpr byte operator~(byte b) noexcept { return byte(~static_cast<unsigned int>(b)); }
template <class IntegerType>
constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept { return b = b << shift; }
template <class IntegerType>
constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept { return b = b >> shift; }
constexpr byte& operator|=(byte& l, byte r) noexcept { return l = l | r; }
constexpr byte& operator&=(byte& l, byte r) noexcept { return l = l & r; }
constexpr byte& operator^=(byte& l, byte r) noexcept { return l = l ^ r; }

这省略了检查IntegerType是否实际上是一个整数(以及前面提到的对象表示支持(,但在其他方面功能完整。

您可能只想使用它而不std::byte,因为您可能会遇到冲突,其中某些文件使用std::byte编译,而其他文件使用 replace 编译,从而导致奇怪的链接器错误。