First of all, code doesn't compile.
error: call of overloaded 'processB(int)' is ambiguous
It kind of suggests that the code is ill-formed. Answer to the first question.
Before I jump into further explanations, I would suggest 2 sources to look at:
- CppReferences page - Constraints and Concepts (C++20)
- CppCon video - BackToBasics: Concepts
Cpp reference article covers lots of ground and goes into great detail about Concepts. However, the language and examples used are sometimes hard to understand. That's where video comes in; Nicolai Josuttis's explanations of Concepts are great.
Going back to the questions in the initial article D1: Core Language — Concepts, Constraint Subsumption, and Overload Resolution.
Code, as I already mentioned, is ill-formed and doesn't compile. Let's try to understand why.
Logically, we have declared similar concepts.
SignedA and SignedB essentially define the same list of requirements for the function overload. But the compiler uses strictly defined rules and follows them even if sometimes it looks dumb to a person. All declared concepts satisfy type
int. It is integral and signed. So when processA(42) and processB(42) are called, the compiler must decide which specialization to use. As I understand it, the process of selecting the correct function overload is done in a few steps. It might not be implemented in the same way, but thinking that way helps to build a mental model.
First, the compiler selects all function overloads that satisfy the requirements of the type. All three concepts in our case work for function calls
processA(42) and processB(42). Then the compiler identifies subsumption relationships between concepts to find which is more constrained. For processA it works:
SignedA subsumes Integral, and Integral doesn't subsume SignedA, which means SignedA is more constrained. The 2nd overload of processA is going to be called. Here, we are finally getting to the main problem. Subsumption doesn't work automatically. It must be clearly defined by the programmer.
SignedA is declared via Integral, and the compiler right away identifies that SignedA subsumes Integral. SignedB, on the other hand, uses standard std::is_integral_v in the declaration and therefore doesn't subsume Integral explicitly. That summarizes it.
Коментарі
Дописати коментар