问题
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?
回答1:
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.
Note that input might include some global state or the object for which a member function is called. Also note that the well-defined behavior might mean throwing an exception.
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.
Note that preconditions are not always easy to verify: For pointers such as int* p, the * operator can be understood to have a narrow contract, because you can only dereference a pointer when it points to a valid object, but it is tricky because there is no easy way to check whether you can do int x = *p or not.
来源:https://stackoverflow.com/questions/51292673/what-is-in-simple-understanding-narrow-contract-and-wide-contract-in-terms-of