Skip to content

Commit a69c304

Browse files
committed
feat: migrate cpp/templates cpp/exceptions from cppref
1 parent 95a439b commit a69c304

File tree

2 files changed

+364
-0
lines changed

2 files changed

+364
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
title: Exceptions
3+
cppdoc:
4+
keys: ["cpp.lang.exceptions"]
5+
---
6+
7+
import { Decl, DeclDoc } from "@components/decl-doc";
8+
import { Desc, DescList, DocLink } from '@components/index';
9+
import { Revision, RevisionBlock } from "@components/revision";
10+
import { DR, DRList } from "@components/defect-report";
11+
import { ParamDoc, ParamDocList } from "@components/param-doc";
12+
import { FeatureTestMacro, FeatureTestMacroValue } from "@components/feature-test-macro";
13+
14+
Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack).
15+
16+
Evaluating a <DocLink src="cpp/language/throw.html#throw_expressions">`throw` expression</DocLink> will throw an exception. Exceptions can also be thrown in <DocLink src="cpp/language/throw.html#throw_expressions">other contexts</DocLink>.
17+
18+
In order for an exception to be caught, the `throw` expression has to be inside a <DocLink src="cpp/language/try">`try` block</DocLink>, and the `try` block has to contain a <DocLink src="cpp/language/catch">handler</DocLink> that matches the type of the exception object.
19+
20+
When declaring a function, the following specification(s) may be provided to limit the types of the exceptions a function may throw:
21+
22+
- <Revision since="C++17"><DocLink src="cpp/language/cpp/language/except_spec">dynamic exception specifications</DocLink></Revision>
23+
- <Revision since="C++11"><DocLink src="cpp/language/cpp/language/noexcept_spec">noexcept specifications</DocLink></Revision>
24+
25+
Errors that arise during exception handling are handled by <DocLink src="cpp/error/terminate">`std::terminate`</DocLink> and <Revision since="C++17"><DocLink src="cpp/error/unexpected">`std::unexpected`</DocLink></Revision>.
26+
27+
## Usage
28+
29+
While `throw` expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to <DocLink src="cpp/utility/program/longjmp">`std::longjmp`</DocLink>), its intended usage is error handling.
30+
31+
### Error handling
32+
33+
Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following[^1] [^2] [^3]:
34+
35+
1. Failures to meet the postconditions, such as failing to produce a valid return value object.
36+
2. Failures to meet the preconditions of another function that must be called.
37+
3. (for non-private member functions) Failures to (re)establish a class invariant.
38+
39+
In particular, this implies that the failures of constructors (see also <DocLink src="cpp/language/raii">RAII</DocLink>) and most operators should be reported by throwing exceptions.
40+
41+
In addition, so-called *wide contract* functions use exceptions to indicate unacceptable inputs, for example, <DocLink src="cpp/string/basic_string/at">`std::basic_string::at`</DocLink> has no preconditions, but throws an exception to indicate index out of range.
42+
43+
### Exception safety
44+
45+
After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized[^4] [^5] [^6], which are strict supersets of each other:
46+
47+
1. *Nothrow (or nofail) exception guarantee* — the function never throws exceptions. Nothrow (errors are reported by other means or concealed) is expected of <DocLink src="cpp/language/destructor">destructors</DocLink> and other functions that may be called during stack unwinding. <Revision since="C++11">The <DocLink src="cpp/language/destructor">destructors</DocLink> are <DocLink src="cpp/language/noexcept">`noexcept`</DocLink> by default.</Revision> Nofail (the function always succeeds) is expected of swaps, <DocLink src="cpp/language/move_constructor">move constructors</DocLink>, and other functions used by those that provide strong exception guarantee.
48+
2. *Strong exception guarantee* — If the function throws an exception, the state of the program is rolled back to the state just before the function call (for example, <DocLink src="cpp/container/vector/push_back">`std::vector::push_back`</DocLink>).
49+
3. *Basic exception guarantee* — If the function throws an exception, the program is in a valid state. No resources are leaked, and all objects' invariants are intact.
50+
4. *No exception guarantee* — If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.
51+
52+
Generic components may, in addition, offer *exception-neutral guarantee*: if an exception is thrown from a template parameter (e.g. from the `Compare` function object of <DocLink src="cpp/algorithm/sort">`std::sort`</DocLink> or from the constructor of `T` in <DocLink src="cpp/memory/shared_ptr/make_shared">`std::make_shared`</DocLink>), it is propagated, unchanged, to the caller.
53+
54+
## Exception objects
55+
56+
While objects of any complete type and cv pointers to `void` may be thrown as exception objects, all standard library functions throw unnamed objects by value, and the types of those objects are derived (directly or indirectly) from <DocLink src="cpp/error/exception">`std::exception`</DocLink>. User-defined exceptions usually follow this pattern.[^7] [^8] [^9]
57+
58+
To avoid unnecessary copying of the exception object and object slicing, the best practice for handlers is to catch by reference.[^10] [^11] [^12] [^13]
59+
60+
## Notes
61+
62+
<FeatureTestMacro name="__cpp_constexpr_exceptions">
63+
<FeatureTestMacroValue value="202411L" since="C++26">
64+
`constexpr` exceptions
65+
</FeatureTestMacroValue>
66+
</FeatureTestMacro>
67+
68+
## External links
69+
70+
[^1]: H. Sutter (2004) [When and How to Use Exceptions](https://www.drdobbs.com/when-and-how-to-use-exceptions/184401836) in Dr. Dobb's
71+
[^2]: H. Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 70
72+
[^3]: C++ Core Guidelines [I.10: Use exceptions to signal a failure to perform a required task](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-except)
73+
[^4]: B. Stroustrup (2000) "The C++ Programming Language" [Appendix E](https://stroustrup.com/3rd_safe.pdf)
74+
[^5]: H. Sutter (2000) "Exceptional C++"
75+
[^6]: D. Abrahams (2001) ["Exception Safety in Generic Components"](https://www.boost.org/community/exception_safety.html)
76+
[^7]: D. Abrahams (2001) ["Error and Exception Handling"](https://www.boost.org/community/error_handling.html)
77+
[^8]: isocpp.org Super-FAQ ["What should I throw?"](https://isocpp.org/wiki/faq/exceptions#what-to-throw)
78+
[^9]: C++ Core Guidelines [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-exception-types)
79+
[^10]: C++ Core Guidelines [E.15: Throw by value, catch exceptions from a hierarchy by reference](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-exception-ref)
80+
[^11]: S. Meyers (1996) "More Effective C++" Item 13
81+
[^12]: isocpp.org Super-FAQ ["What should I catch?"](https://isocpp.org/wiki/faq/exceptions#what-to-catch)
82+
[^13]: H. Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73
Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
---
2+
title: Templates
3+
cppdoc:
4+
keys: ["cpp.lang.templates"]
5+
---
6+
7+
import { Decl, DeclDoc } from "@components/decl-doc";
8+
import { Desc, DescList, DocLink } from '@components/index';
9+
import { Revision, RevisionBlock } from "@components/revision";
10+
import { DR, DRList } from "@components/defect-report";
11+
import { ParamDoc, ParamDocList } from "@components/param-doc";
12+
13+
A template is a C++ entity that defines one of the following:
14+
15+
- a family of classes (<DocLink src="cpp/language/class_template">class template</DocLink>), which may be <DocLink src="cpp/language/member_template">nested classes</DocLink>
16+
- a family of functions (<DocLink src="cpp/language/function_template">function template</DocLink>), which may be <DocLink src="cpp/language/member_template">member functions</DocLink>
17+
18+
19+
- <Revision since="C++11">an alias to a family of types (<DocLink src="cpp/language/type_alias">alias template</DocLink>)</Revision>
20+
21+
22+
- <Revision since="C++14">a family of variables (<DocLink src="cpp/language/variable_template">variable template</DocLink>)</Revision>
23+
24+
25+
- <Revision since="C++20">a concept (<DocLink src="cpp/language/constraints">constraints and concepts</DocLink>)</Revision>
26+
27+
Templates are parameterized by one or more <DocLink src="cpp/language/template_parameters">template parameters</DocLink>, of three kinds: type template parameters, constant template parameters, and template template parameters.
28+
29+
When template arguments are provided, or, for <DocLink src="cpp/language/function_template#Template_argument_deduction">function</DocLink> <Revision since="C++17">and <DocLink src="cpp/language/class_template_argument_deduction">class</DocLink></Revision> templates only, deduced, they are substituted for the template parameters to obtain a *specialization* of the template, that is, a specific type or a specific function lvalue.
30+
31+
Specializations may also be provided explicitly: <DocLink src="cpp/language/template_specialization">full specializations</DocLink> are allowed for class<Revision since="C++14">, <DocLink src="cpp/language/template_specialization">variable</DocLink></Revision> and function templates, <DocLink src="cpp/language/partial_specialization">partial specializations</DocLink> are only allowed for class templates<Revision since="C++14"> and <DocLink src="cpp/language/partial_specialization">variable templates</DocLink></Revision>.
32+
33+
When a class template specialization is referenced in context that requires a complete object type, or when a function template specialization is referenced in context that requires a function definition to exist, the template is *instantiated* (the code for it is actually compiled), unless the template was already explicitly specialized or explicitly instantiated. Instantiation of a class template does not instantiate any of its member functions unless they are also used. At link time, identical instantiations generated by different translation units are merged.
34+
35+
The definition of a class template must be visible at the point of implicit instantiation, which is why template libraries typically provide all template definitions in the headers (e.g., [most boost libraries are header-only](https://www.boost.org/doc/libs/release/more/getting_started/unix-variants.html#header-only-libraries)).
36+
37+
## Syntax
38+
39+
<DeclDoc>
40+
<Decl slot="decl">
41+
```cpp
42+
template <parameter-list> requires-clause(optional)</span> declaration
43+
```
44+
</Decl>
45+
</DeclDoc>
46+
47+
<DeclDoc>
48+
<Decl slot="decl">
49+
```cpp
50+
export template <parameter-list> declaration
51+
```
52+
</Decl>
53+
<Revision until="C++11"></Revision>
54+
</DeclDoc>
55+
56+
<DeclDoc>
57+
<Decl slot="decl">
58+
```cpp
59+
template <parameter-list> concept concept-name = constraint-expression;
60+
```
61+
</Decl>
62+
<Revision since="C++20"></Revision>
63+
</DeclDoc>
64+
65+
66+
<ParamDocList>
67+
<ParamDoc name="parameter-list">
68+
a non-empty comma-separated list of the template parameters, each of which is either constant parameter, a type parameter, a template parameter, or a parameter pack of any of those(since C++11).
69+
</ParamDoc>
70+
<ParamDoc name="requires-clause">
71+
(since C++20) a requires-clause that specifies the constraints on the template arguments.
72+
</ParamDoc>
73+
<ParamDoc name="declaration">
74+
declaration of a class (including struct and union), a member class or member enumeration type, a function or member function, a static data member at namespace scope, a variable or static data member at class scope(since C++14), or an alias template(since C++11). It may also define a template specialization.
75+
</ParamDoc>
76+
<ParamDoc name="concept-name">
77+
concept-name
78+
</ParamDoc>
79+
<ParamDoc name="constraint-expression">
80+
see constraints and concepts
81+
</ParamDoc>
82+
</ParamDocList>
83+
84+
<RevisionBlock until="C++11">export was an optional modifier which declared the template as exported (when used with a class template, it declared all of its members exported as well). Files that instantiated exported templates did not need to include their definitions: the declaration was sufficient. Implementations of export were rare and disagreed with each other on details. </RevisionBlock>
85+
> This section is incomplete.\
86+
> **Reason:** core syntax, template parameters, and instantiations, take content common between class_template and function_template
87+
88+
## Template identifiers
89+
90+
A template identifier has one of the following syntaxes:
91+
92+
<DeclDoc>
93+
<Decl slot="decl">
94+
```cpp
95+
template-name<template-argument-list(optional)>
96+
```
97+
</Decl>
98+
99+
A *simple template identifier*.
100+
</DeclDoc>
101+
<DeclDoc>
102+
<Decl slot="decl">
103+
```cpp
104+
operator op<template-argument-list(optional)>
105+
```
106+
</Decl>
107+
108+
An operator function template identifier.
109+
</DeclDoc>
110+
<DeclDoc>
111+
<Decl slot="decl">
112+
```cpp
113+
operator "" identifier<template-argument-list(optional)>
114+
```
115+
</Decl>
116+
117+
A literal operator function template identifier. <Revision since="C++11" traits={[{ trait: "deprecated", since:"C++23"}]}></Revision>
118+
</DeclDoc>
119+
<DeclDoc>
120+
<Decl slot="decl">
121+
```cpp
122+
operator user-defined-string-literal<template-argument-list(optional)>
123+
```
124+
</Decl>
125+
126+
A user-defined string literal operator. <Revision since="C++11"></Revision>
127+
</DeclDoc>
128+
129+
A simple template identifier that names a class template specialization names a class.
130+
131+
A template identifier that names an alias template specialization names a type.
132+
133+
A template identifier that names a function template specialization names a function.
134+
135+
If all following conditions are satisfied, a template identifier is *valid*:
136+
137+
- There are at most as many arguments as there are parameters<Revision since="C++11"> or a parameter is a template <DocLink src="cpp/language/parameter_pack">parameter pack</DocLink></Revision>
138+
- There is an argument for each non-deducible<Revision since="C++11"> non-pack</Revision> parameter that does not have a default template argument
139+
- Each template argument matches the corresponding template parameter
140+
- Substitution of each template argument into the following template parameters (if any) succeeds
141+
142+
- <Revision since="C++20"> If the template identifier is <DocLink src="/cpp/language/dependent_name">non-dependent</DocLink>, the associated constraints are satisfied as specified below</Revision>
143+
144+
An invalid simple template id is a compile-time error, unless it names a function template specialization (in which case <DocLink src="cpp/language/sfinae">SFINAE</DocLink> may apply).
145+
146+
```cpp
147+
template<class T, T::type n = 0>
148+
class X;
149+
150+
struct S
151+
{
152+
using type = int;
153+
};
154+
155+
using T1 = X<S, int, int>; // error: too many arguments
156+
using T2 = X<>; // error: no default argument for first template parameter
157+
using T3 = X<1>; // error: value 1 does not match type-parameter
158+
using T4 = X<int>; // error: substitution failure for second template parameter
159+
using T5 = X<S>; // OK
160+
```
161+
162+
<RevisionBlock since="C++20">
163+
When the `template-name` of a simple template id names a constrained non-function template or a constrained template template parameter, but not a member template that is a member of an unknown specialization, and all template arguments in the simple template id are non-dependent, the associated constraints of the constrained template must be satisfied:
164+
165+
```cpp
166+
template<typename T>
167+
concept C1 = sizeof(T) != sizeof(int);
168+
169+
template<C1 T>
170+
struct S1 {};
171+
172+
template<C1 T>
173+
using Ptr = T*;
174+
175+
S1<int>* p; // error: constraints not satisfied
176+
Ptr<int> p; // error: constraints not satisfied
177+
178+
template<typename T>
179+
struct S2 { Ptr<int> x; }; // error, no diagnostic required
180+
181+
template<typename T>
182+
struct S3 { Ptr<T> x; }; // OK, satisfaction is not required
183+
184+
S3<int> x; // error: constraints not satisfied
185+
186+
template<template<C1 T> class X>
187+
struct S4
188+
{
189+
X<int> x; // error, no diagnostic required
190+
};
191+
192+
template<typename T>
193+
concept C2 = sizeof(T) == 1;
194+
195+
template<C2 T> struct S {};
196+
197+
template struct S<char[2]>; // error: constraints not satisfied
198+
template<> struct S<char[2]> {}; // error: constraints not satisfied
199+
```
200+
</RevisionBlock>
201+
202+
If all following conditions are satisfied, two template identifiers are *same*:
203+
204+
- Their `template-name`s or operators refer to the same template
205+
- Their corresponding type template arguments are the same type
206+
- The template parameter values determined by their corresponding constant template arguments are <DocLink src="cpp/language/template_parameters#Template_argument_equivalence">template-argument-equivalent</DocLink>
207+
- Their corresponding template template arguments refer to the same template
208+
209+
Two template identifier that are the same refer to the same<Revision since="C++14"> variable,</Revision> class, or function.
210+
211+
## Templated entity
212+
213+
A *templated entity* (or, in some sources, "temploid") is any entity that is defined<Revision since="C++11"> (or, for a <DocLink src="/cpp/language/lambda">lambda expression</DocLink>, created)</Revision> within a template definition. All of the following are templated entities:
214+
215+
- a class/function<Revision since="C++14">/variable</Revision> template
216+
217+
218+
- <Revision since="C++20">a <DocLink src="cpp/language/constraints">concept</DocLink> </Revision>
219+
220+
- a member of a templated entity (such as a non-template member function of a class template)
221+
- an enumerator of an enumeration that is a templated entity
222+
- any entity defined or created within a templated entity: a local class, a local variable, a friend function, etc
223+
224+
- <Revision since="C++11">the closure type of a <DocLink src="cpp/language/lambda">lambda expression</DocLink> that appears in the declaration of a templated entity</Revision>
225+
226+
For example, in
227+
228+
```cpp
229+
template<typename T>
230+
struct A
231+
{
232+
void f() {}
233+
};
234+
```
235+
236+
the function `A::f` is not a function template, but is still considered to be templated.
237+
238+
A *templated function* is a function template or a function that is templated.
239+
240+
A *templated class* is a class template or a class that is templated.
241+
242+
<Revision since="C++14">A *templated variable* is a variable template or a variable that is templated. </Revision>
243+
244+
## Keywords
245+
246+
<DocLink src="cpp/keyword/template">template</DocLink>,
247+
<DocLink src="cpp/keyword/export">export</DocLink>
248+
249+
## Defect reports
250+
251+
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
252+
253+
<DRList>
254+
<DR kind="cwg" id={2293} std="C++98">
255+
<Fragment slot="behavior-published">
256+
the rules of determining whether a template identifier is valid were not provided
257+
</Fragment>
258+
<Fragment slot="correct-behavior">
259+
provided
260+
</Fragment>
261+
</DR>
262+
<DR kind="cwg" id={2682} std="C++98">
263+
<Fragment slot="behavior-published">
264+
the definitions of templated function/template class (C++98)/templated variable (C++14) were missing
265+
</Fragment>
266+
<Fragment slot="correct-behavior">
267+
added
268+
</Fragment>
269+
</DR>
270+
<DR kind="cwg" id={2308} std="C++98">
271+
<Fragment slot="behavior-published">
272+
two template identifiers were different if their corresponding constant template arguments are not template-argument-equivalent
273+
</Fragment>
274+
<Fragment slot="correct-behavior">
275+
they are different if their corresponding constant template parameter values are not template-argument-equivalent
276+
</Fragment>
277+
</DR>
278+
</DRList>
279+
280+
## See also
281+
282+
<DocLink src="c/language/generic">C documentation</DocLink> for __Generic selection__

0 commit comments

Comments
 (0)