Created
December 5, 2022 17:03
-
-
Save mralfarrakhan/71ce052a21a30d2ac43855005ddead94 to your computer and use it in GitHub Desktop.
some experiment with functional and template to note
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <vector> | |
| #include <functional> | |
| #include <ranges> | |
| #include <string> | |
| template <template<class> class I, class T> | |
| requires std::ranges::output_range<I<T>, T> && std::convertible_to<T, double> | |
| void foriter(I<T>& iterable, const std::function<void(T&)>& func) | |
| { | |
| for (T& e : iterable) { | |
| func(e); | |
| } | |
| } | |
| template <template<class> class I, class T, class F> | |
| requires std::ranges::output_range<I<T>, T> && std::convertible_to<T, double> | |
| void sforiter(I<T>& iterable, const F& func) | |
| { | |
| for (T& e : iterable) { | |
| (std::function<void(T&)>(func))(e); | |
| } | |
| } | |
| template<typename I> | |
| requires std::ranges::range<I> | |
| void print(I iterable, std::string delim = "\n", std::string endl = "\n") { | |
| for (const auto& e : iterable) { | |
| std::cout << e << delim; | |
| } | |
| std::cout << endl; | |
| } | |
| template<typename T> | |
| requires std::convertible_to<T, double> | |
| void change(T& n) { | |
| n = 3.14; | |
| } | |
| int main() { | |
| std::vector<double> av(10, 10); | |
| print(av, " "); | |
| using av_value_t = decltype(av[0]); | |
| sforiter(av, | |
| [](av_value_t& e) { | |
| e = e/(e+1); | |
| } | |
| ); | |
| print(av, " "); | |
| std::function<void(av_value_t&)> fungus(&change<av_value_t>); | |
| foriter(av, fungus); | |
| print(av, " "); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment