Debian Codegraph @

yo/advancedtemplates/concepts/specializations.yo

raw
1 Class templates can be (partially) specialized. Specializations are commonly
2 used to fine-tune implementations for specific types. Concepts can also be
3 used when specializations are defined. Consider a tt(struct Handler) having
4 the following generic implementation:
5 verbinsert(-s4 //generic examples/specializations.cc)
6
7 In addition to possibly type-related specializations (like a tt(struct
8 Handler<Tp *> ...)) a specialization requiring the availability of the
9 addition operator on tt(Tp) can be defined by requiring the concept
10 tt(Addable):
11 verbinsert(-s4 //addable examples/specializations.cc)
12
13 When used in the following program (assuming all required headers were
14 included), the first line of the output shows em(Generic Handler), while
15 the second line shows em(Handler for types supporting operator+):
16 verbinsert(-s4 //use examples/specializations.cc)
17
18 The compiler, compiling tt(main's) first statement, first looks for
19 a specialized version of tt(Handler). Although it finds one, that
20 specialization requires the availability of tt(operator+). As that operator is
21 not available for tt(std::vector) the compiler does not use that
22 specialization. Had this been the only available implementation, then the
23 compiler would have reported a tt(constraints not satisfied) error. However,
24 there's still the generic definition which em(can) be used for
25 tt(std::vector). Therefore the compiler uses the generic definition (which is
26 at the same time provides a nice illustration of the SFINAE (cf. section
27 ref(SFINAE)) principle).
28
29 When instantiating the second tt(Handler) object the addition operator em(is)
30 available, and so in that case the compiler selects the specialized version:
31 where available, specializations are used; if not, then generic template
32 definitions are used.