|
172 | 172 | \end{cppcode*}
|
173 | 173 | \end{frame}
|
174 | 174 |
|
| 175 | +\begin{advanced} |
| 176 | + |
| 177 | +\begin{frame}[fragile] |
| 178 | + \frametitlecpp[17]{Non-type template parameter - auto} |
| 179 | + \small |
| 180 | + \begin{cppcode} |
| 181 | + template <auto Area> |
| 182 | + struct Shape { |
| 183 | + static constexpr auto area() { return Area; } |
| 184 | + }; |
| 185 | + // we use a type here to hold values |
| 186 | + using Area51 = Shape<51>; |
| 187 | + |
| 188 | + template<typename Base> |
| 189 | + struct Prism { |
| 190 | + double height; |
| 191 | + auto volume() const { return height * Base::area(); } |
| 192 | + }; |
| 193 | + Prism<Area51> prism1{2.}; |
| 194 | + Prism<Shape<3.14>> prism2{3.}; // C++20 |
| 195 | + \end{cppcode} |
| 196 | + \begin{block}{} |
| 197 | + \begin{itemize} |
| 198 | + \item Using a type to hold a value is a frequently trick |
| 199 | + \begin{itemize} |
| 200 | + \item See e.g.\ \mintinline{cpp}{std::integral_constant} |
| 201 | + \end{itemize} |
| 202 | + \end{itemize} |
| 203 | + \end{block} |
| 204 | +\end{frame} |
| 205 | + |
| 206 | +\begin{frame}[fragile] |
| 207 | + \frametitlecpp[20]{Non-type template parameter - literal types} |
| 208 | + \footnotesize |
| 209 | + \begin{cppcode*}{} |
| 210 | + template <typename T> struct Shape { |
| 211 | + T area_; |
| 212 | + constexpr auto area() const { return area_; } |
| 213 | + }; |
| 214 | + template<auto Base, typename T> struct RightPrism { |
| 215 | + T height; |
| 216 | + T volume() const { return height * Base.area(); } |
| 217 | + constexpr T area() const { ... } |
| 218 | + }; |
| 219 | + RightPrism<Shape{60.}, double> prism1{3.}; |
| 220 | + |
| 221 | + template<unsigned int N> struct Polygon { |
| 222 | + float radius; |
| 223 | + constexpr float area() const { ... } |
| 224 | + }; |
| 225 | + RightPrism<Polygon<4>{2.f}, double> prism2{3.}; |
| 226 | + RightPrism<RightPrism<Shape<42>, int>{3}, float> hyperprism{3.f}; |
| 227 | + \end{cppcode*} |
| 228 | + \begin{block}{} |
| 229 | + Enormous potential! We have yet to see what people will do with it! |
| 230 | + \end{block} |
| 231 | +\end{frame} |
| 232 | + |
| 233 | +\end{advanced} |
| 234 | + |
175 | 235 | \begin{frame}[fragile]
|
176 | 236 | \frametitlecpp[98]{Template specialization}
|
177 | 237 | \begin{block}{Specialization}
|
|
0 commit comments