2 ms·
I'd like to know why this was downvoted. (Edit: other than the fact that the exponent should be unsigned int :/) The whole point of encapsulation is to be able
by Sharlin 12y ago
I'd like to know why this was downvoted. (Edit: other than the fact that the exponent should be unsigned int :/)
The whole point of encapsulation is to be able to write data types that have invariants other than those offered by the machine-level types. If you want a type T that satisfies the predicate
∀n∈T: ∃k∈N: n = 2^k
then you write a type that only provides operations that maintain the constraint. In this case, for instance, construction from k and multiplication by another T. As I said, some languages like C++ do also allow things such as compile-time conversion of an unconstrained constant integer into a power-of-two integer, with a compile error if the constraint isn't satisfied, but in my opinion that's mostly syntactic sugar. Would be nice if you could simply write, say,
type intPowerOfTwo = unsigned int where ∀intPowerOfTwo n: ∃unsigned int k: n = 2^k
but what about the unsigned int operations, such as addition, that do not maintain the invariant? Should the type system include a general theorem prover that can deduce which operations are allowed?
However, I understand this was simply an example and do agree that expressive and powerful type systems are certainly a very useful tool. C++ template metaprogramming (pretty much computing with types as values) is very impressive even if horribly ad hoc and the concepts feature (constrained templates), if ever actually implemented, will make all kinds of things easier.
http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29 http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29
https://isocpp.org/blog/2013/02/concepts-lite-constraining-templates-with-predicates-andrew-sutton-bjarne-s https://isocpp.org/blog/2013/02/concepts-lite-constraining-t...