c++ - 如何在 C++ 中强类型整数?

标签 c++

考虑这个 C++ 代码片段:

using BookID = int;
using CustomerID = int;

BookID bookId;
CustomerID custId;

void sub() {
   bookId = custId;
}

这段代码编译得很好。但是,我希望编译器将此标记为错误,即一种 id 类型的实例正在分配给另一种类型。

是否有一种简单的方法来使用 C++ 的强大功能(可能使用通用模板):

  1. 确保编译器可以将其标记为错误
  2. 团队中的任何开发人员都易于使用
  3. 希望没有太多的运行时开销

在我当前的项目中,我要处理大约 15 种不同的 ID 类型。问候。

最佳答案

您可以只使用简单的 template struct 并在必要时扩展它(使用 accessor、ctor 等使 id 私有(private)):

enum IdType {
    Book,
    Customer
};
 
template <IdType Type>
struct Id {
    int m_id;
};

using BookId = Id<Book>;
using CustomerId = Id<Customer>;
 

Live example

您可以使用标记类型而不是 enum 值,这会使它更灵活但可能组织性较差 - 您的 id 类型可以在本地定义,而不是强制在一个地方枚举所有类型:

template <typename T>
struct Id {
    int m_id;
};

struct BookIdTag;
using BookId = Id<BookIdTag>;

(感谢@N.Shead)

关于c++ - 如何在 C++ 中强类型整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63821852/

相关文章:

c++ - 找不到“iostream”文件

java - 将 jobjectarray 转换为 vector<uint8_t>

c++ - 没有给出测试用例时如何输入?

C++ 递归变量

c++ - 使用 Win32 和 UWP/Xbox 平台支持管理 C++ 应用程序的最佳实践?

c++ - 收到错误 clang : error: linker command failed with exit code 1 (use -v to see invocation) while compile C++ file from terminal

c++ - 为什么 list<unique_ptr> 中的 unique_ptr 的 std::move() 没有真正 move 它?

c++ - 融合多个 Haar 分类器进行人脸检测

c++ - 硬件断点可以写内存吗?

c++ - 为什么函数声明返回 bool 在我的 C++ 项目中没有编译?