aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/development
diff options
context:
space:
mode:
authorJohannes Stoelp <johannes.stoelp@gmail.com>2022-08-24 18:09:52 +0200
committerJohannes Stoelp <johannes.stoelp@gmail.com>2022-08-24 18:09:52 +0200
commite6f439cb43ee51b13ed4d29ec84ac5450556b163 (patch)
tree91c61c93cd3873c57a15448d4ef376d188f7706c /src/development
parent6f6fef7bb61712038220a7607447d38689ad6978 (diff)
downloadnotes-e6f439cb43ee51b13ed4d29ec84ac5450556b163.tar.gz
notes-e6f439cb43ee51b13ed4d29ec84ac5450556b163.zip
c++: add any_of meta fn example
Diffstat (limited to 'src/development')
-rw-r--r--src/development/c++.md14
-rw-r--r--src/development/c++/meta.cc4
-rw-r--r--src/development/c++/meta3.cc22
3 files changed, 39 insertions, 1 deletions
diff --git a/src/development/c++.md b/src/development/c++.md
index 4ce1538..aff9ccd 100644
--- a/src/development/c++.md
+++ b/src/development/c++.md
@@ -16,7 +16,19 @@ typename decltype(foo)::_;
{{#include c++/meta.cc:3:}}
```
-## [SFINAE][sfinae] example ([enable_if][enable-if])
+## Example: `is_any_of` template meta function
+
+```cpp
+{{#include c++/meta3.cc:3:}}
+```
+
+## Example: [SFINAE][sfinae] ([enable_if][enable-if])
+
+Provide a single entry point `Invoke` to call some `Operations`.
+Use `enable_if` to enable/disable the template functions depending on the two
+available traits an operation can have:
+- Operation returns a result
+- Operation requires a context
```cpp
{{#include c++/meta2.cc:3:}}
diff --git a/src/development/c++/meta.cc b/src/development/c++/meta.cc
index e674cfd..efb3b22 100644
--- a/src/development/c++/meta.cc
+++ b/src/development/c++/meta.cc
@@ -2,6 +2,8 @@
#include <iostream>
+// -- Example 1 - print template value arguments.
+
// Base case with one parameter.
template<int P>
void show_int() {
@@ -15,6 +17,8 @@ void show_int() {
show_int<P1, Params...>();
}
+// -- Example 2 - print values of different types.
+
// Base case with one parameter.
template<typename T>
void show(const T& t) {
diff --git a/src/development/c++/meta3.cc b/src/development/c++/meta3.cc
new file mode 100644
index 0000000..5dce54a
--- /dev/null
+++ b/src/development/c++/meta3.cc
@@ -0,0 +1,22 @@
+// Copyright (C) 2022 johannst
+
+#include <type_traits>
+
+template<typename T, typename... U>
+struct any_of : std::false_type {};
+
+// Found our type T in the list of types U.
+template<typename T, typename... U>
+struct any_of<T, T, U...> : std::true_type {};
+
+// Pop off the first element in the list of types U,
+// since it didn't match our type T.
+template<typename T, typename U0, typename... U>
+struct any_of<T, U0, U...> : any_of<T, U...> {};
+
+// Convenience template variable to invoke meta function.
+template<typename T, typename... U>
+constexpr bool any_of_v = any_of<T, U...>::value;
+
+static_assert(any_of_v<int, char, bool, int>, "");
+static_assert(!any_of_v<int, char, bool, float>, "");