|
Boost : |
Subject: [boost] [contract] toward N3351 concepts
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2012-09-26 15:00:18
Hello all,
I'm reading N3351:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf
It's a bottom-up approach to define concepts starting from what's
needed by STL algorithms. So far so good--I like it probably more than
C++0x concept proposals--N331 is simpler :) However, N3351 STL design
is not fully compatible with the current STL specifications--maybe
N3351 is better, more mathematically sound?
In N3351, concepts are boolean constants:
``We can define concepts as simple (constant) Boolean expressions.
This is useful when building
constraints predicated on non-syntactic and non-semantics properties of types.``
So I can implement concepts in C++11 as boolean meta-functions using
expression SFINAE to check the requirements and enable_if to disable
generic algorithms when the instantiated types don't model the
concepts (i.e., the concept's boolean meta-function is false). For
example, that's the case for the bool{a== b} and bool{a!=b}
expressions of the EqualityComparable concept below.
However, N3351 says that axioms should not be checked by the compiler...
``Axioms express the semantics of a concepts required syntax; they
are assumed to be true and
must not be checked by the compiler beyond conformance to the C++
syntax. Any additional
checking is beyond the scope of the compilers translation
requirements. The compiler must not
generate code that evaluates axioms as preconditions, either. This
could lead to program errors
if the evaluated assertions have side effects. For example, asserting
that distance(first, last) > 1
when the type of those iterators is istream_iterator will consume the
first element of the range,
causing the assertion to pass, but the algorithm to have undefined behavior.''
So what am I supposed to do with axioms? Do nothing? Axioms are just
"comments" that document the semantic?
For example:
``
concept EqualityComparable<typename T> =
requires (T a, T b, T c) {
bool { a == b };
bool { a != b };
axiom { a == b <=> eq(a, b); } // true equality
axiom {
a == a; // reflexive
a == b => b == a; // symmetric
a == b && b == c => a == c; // transitive
}
axiom { a != b <=> !(a == b); } // complement
};
So, EqualityComparable<T> is true if T
1. has == and != with result types that can be converted to bool
2. == compares for true equality
3. == is reflexive, symmetric, and transitive
4. != is the complement of ==
However, the compiler can only check the first of these conditions.
The rest must be verified
through other means (i.e. manually).
''
Thanks,
--Lorenzo
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk