c++ - What are constrained templates? -
herb sutters mentioned constrained templates (a.k.a. concepts lite) in talk: modern c++: need know.
i know boost has concepts package in ages, allows 1 pretty print error messages, when template deduction mechanism fails find operators, functions or has access violation patterns.
i've encountered mentions on isocpp blog there experimental branch of gcc implementing document proposing concepts lite. looking through current c++14 draft couldn't find hints whether part of c++14
.
so questions simple:
- will concepts lite part of c++14? (reference in standard preferred. not find one, , i'm not familiar standard.)
- what correct syntax of it? (the proposal , slides of herb diverge here , don't know 1 more date)
- could give minimal example of constraint (predicate) , constrained template?
note: if wait long enough i'll try gcc branch running , can @ least experimental implementation, not imply correctness of syntax.
concepts lite "constraints" part of full concepts design c++. described in great detail in n3701 "concepts lite". chapter 2 short tutorial runs through core principles , application, great folks don't want read through 56 pages.
concepts lite not part of c++14, released separate technical specification later year. latest rough draft ts wording n3929 "concepts lite specification".
there few different constraint syntax variants. code example herb used in talk:
auto mean(const sequence& seq) { auto n = 0.0; (auto x : seq) n += x; return n / seq.size(); }
is referred "terse syntax" since it's shorter equivalent of verbose syntax:
template <typename __t> requires sequence<__t>() auto mean(const __t& seq) { auto n = 0.0; (auto x : seq) n += x; return n / seq.size(); }
they both indicate function template mean
can instantiated type models sequence
concept. sake of simplicity, lets assume requirements sequence
our implementation of mean
needs: (a) members begin
& end
return iterators, , (b) member function size
returns integral type. define concept as:
template <typename t> concept bool sequence() { return requires(t t) { {t.size()} -> integral; {t.begin()} -> inputiterator; {t.end()} -> inputiterator; requires same<decltype(t.begin()), decltype(t.end())>(); } }
assuming straight-forward definitions of integral
, inputiterator
, , same
. concept definition ensures that, invented value t
of type t
being tested:
t.size()
valid expression, , returns type modelsintegral
concept.t.begin()
valid, , returns type modelsinputiterator
.- same
t.end()
. - the
inputiterator
returnedt.begin()
has same type returnedt.end()
.
Comments
Post a Comment