我应该利用强大的打字来确保在编译时确保正确性

How much should I leverage strong typing to ensure correctness at compile time?

本文关键字:确保 编译 正确性 我应该      更新时间:2023-10-16

内置类型(以及STD的类型)在任何地方都用作函数和构造函数的参数,而这些类型的每个实例并非每个实例都是有效的输入。

示例:

// There is no guarantee that url is actually a url
void make_http_request(const std::string& url); 
// Here we know that it must be a url
void make_http_request(const url& url);
// There is no way of knowing if this is the correct mutex to lock
void insert_into_db(std::mutex mutex);
// Here we know we have the correct mutex
void insert_into_db(db_mutex mutex);

当然,这绝对不能用于您无法控制的对象的属性。例如,您可以做一个connected_socket类,但是如果同伴关闭连接,则类将成为谬论。但是,可以使用它来确保IPv4 UDP套接字永远不会尝试sendto() IPv6端点。

您做的越多,您可以确保您的程序在编译时间有效(谁不喜欢?)。这种做法有什么问题吗?什么是弊端,它们值得吗?

如果这是一个用另一个名称出现的概念,我只是找不到它。

C 核心指南中有有关此的指南:

i.4:精确且强烈键入

原因

类型是最简单,最佳的文档,具有明确的含义,并保证在编译时检查。另外,精确键入的代码通常会更好地优化。

它提供了一些例子。

并没有真正谈论多远。