如果我想在没有更新编译器的情况下使用新功能,该怎么办?
What shall I do if I want use new feature without update compiler?
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 编译,从而导致奇怪的链接器错误。
相关文章:
- c++20[[no.unique_address]]中的新功能是什么
- 如果我想在没有更新编译器的情况下使用新功能,该怎么办?
- 重载算子新功能的限制
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- 如何组织 git 工作流以修复错误并同时引入新功能
- 新功能"synchronized"块在C++中提供了什么优势?
- C++17 'inline variable' vs 'extern' 关键字继承自 C 的新功能
- 如何制作新功能并将其传递到另一个功能
- 我不能在函数中使用新功能C++构建
- 是否可以保证C++标准库容器调用可替换的新功能
- 向类添加新功能
- 具有新功能的 C++ 动态分配
- 避免每次要引入新功能时都使用新类
- Linux 中的新功能后没有变化
- 如果priority_queue的容器没有push_back功能怎么办
- C++11 是否支持 C11 的新功能?
- C++中的新功能语法
- 用户定义分配器的非标准库放置新功能
- 为什么 C++ 中的新功能在失败时不返回 NULL。
- 我正在使用放置新功能和虚拟功能;为什么我的虚拟功能表有误?