From 99c1f88e7396ee87a812f8d114aac8d903eb7afb Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Wed, 28 Sep 2022 22:10:29 +0200 Subject: c++: pre c++20 concept example --- src/development/c++.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/development/c++.md') diff --git a/src/development/c++.md b/src/development/c++.md index b42a263..1cc4003 100644 --- a/src/development/c++.md +++ b/src/development/c++.md @@ -32,9 +32,35 @@ available traits an operation can have: ```cpp {{#include c++/meta2.cc:3:}} +``` + +## Example: Concepts pre c++20 + +Prior to c++20's concepts, `SFINAE` and `std::void_t` can be leveraged to build +something similar allowing to define an interface (aka trait) for a template +parameter. +```cpp +{{#include c++/concepts-11.cc:3:}} ``` +The main mechanic can be explained with the following reduced example. If one +of the `decltype(std:declval...` expressions is ill-formed, the template +specialization for `is_valid` will be removed from the candidate set due to +[SFINAE][sfinae]. +```cpp +template +struct is_valid : std::false_type {}; + +template +struct is_valid().some_fun1()), + decltype(std::declval().some_fun2()) + >> : std::true_type {}; +``` +> `std::declval()` creates an instance of type T in an unevaluated context. + + [gist-strict-asliasing]: https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8 [parameter-pack]: https://en.cppreference.com/w/cpp/language/parameter_pack [enable-if]: https://en.cppreference.com/w/cpp/types/enable_if -- cgit v1.2.3