While walking through some c++11
concepts, I came across the terms narrow contract
and wide contract
.
But I failed to figure out a simple function example(s) which is/are written for these contracts.
Can I see a simple function example that distinguishes between these two contracts?
Wide contract functions have well-defined behavior for all possible inputs, while narrow contracts mean that the functions can only be called when certain preconditions are met.
Some caveats:
For example, std::vector<int>
-s .size()
member function has a wide contract because it can be called on any instance of a vector (as in std::vector<int> v; /* anything can happen with v here... */; auto s = v.size();
is always valid). The operator[](size_t index)
(as in int x = v[10]
) has a narrow contract, because it can only be called with a parameter that is less than .size()
, otherwise it is undefined. The .at(size_t i)
member function (as in int y = v.at(10)
) however has a wide contract, because it is specified to throw an exception when the index is out of range.
Preconditions are not always easy to verify: For pointers such as int* p
, the *
operator has a narrow contract, because you can only dereference a pointer when it points to a valid object, but there is no general way to verify a pointer before dereferencing it.