Strongly Typing with usings and typedef
In programming, strongly typing ensures that data is handled in accordance with its defined type, preventing errors due to unexpected type conversions. This question focuses on achieving strong typing for identifiers in a project while preserving functionality and compatibility with containers like maps.
Using Structs to Enforce Type Constraints
To meet these requirements, a struct-based solution can be used. The provided code defines structs (string_id) that encapsulate string values with added type information through the use of tags. These tags are unique for each type of identifier, such as portal_tag or cake_tag. This allows for type-safe comparisons and guarantees that identifiers of different types cannot be assigned to one another.
Example Usage
using PortalId = string_id<portal_tag>; using CakeId = string_id<cake_tag>; PortalId portal_id("2"); CakeId cake_id("is a lie"); // OK, same type std::map<CakeId, PortalId> p_to_cake; // OK, converting a PortalId to a CakeId std::unordered_map<CakeId, PortalId> hashed_ptocake; hashed_ptocake.emplace(CakeId("foo"), PortalId("bar")); // Compiler error, mixing types p_to_cake[portal_id] = cake_id; // COMPILER ERROR
Additional Features
The improved version of the code adds functionality for hash maps, streaming to ostream, and custom string conversions. This enables seamless usage of type-safe identifiers in a wide range of contexts.
Conclusion
This solution effectively achieves strong typing for identifiers while preserving their usability with containers. By utilizing structs and tags, it enforces type constraints, preventing errors stemming from type mismatches. The included features provide added versatility and facilitate seamless integration into existing codebases.
The above is the detailed content of How can I achieve strong typing for identifiers while maintaining compatibility with containers like maps?. For more information, please follow other related articles on the PHP Chinese website!