Created
January 4, 2024 15:35
-
-
Save kbridge/a5333f8204bb1c97384c6817f4c03628 to your computer and use it in GitHub Desktop.
demostratse fold expressions introduced C++17 (requires C++20 to run :D)
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 <format> | |
#include <iostream> | |
#include <string> | |
#include <string_view> | |
class Factor | |
{ | |
public: | |
Factor(std::string_view representation) : | |
m_representation(representation) | |
{ | |
} | |
friend Factor operator*(const Factor &a, const Factor &b) | |
{ | |
return Factor(std::format("({} * {})", a.m_representation, b.m_representation)); | |
} | |
friend std::ostream &operator<<(std::ostream &os, const Factor &obj) | |
{ | |
return os << obj.m_representation; | |
} | |
private: | |
std::string m_representation; | |
}; | |
template<typename... Ts> | |
auto product_left_prime(Ts... a) | |
{ | |
return (... * a); // parenthesis is mandatory | |
} | |
template<typename... Ts> | |
auto product_right_prime(Ts... a) | |
{ | |
return (a * ...); // parenthesis is mandatory | |
} | |
template<typename T, typename... Ts> | |
auto product_left(T init, Ts... xs) | |
{ | |
return (init * ... * xs); | |
} | |
template<typename T, typename... Ts> | |
auto product_right(T init, Ts... xs) | |
{ | |
return (xs * ... * init); | |
} | |
int main() | |
{ | |
std::cout << Factor("a") * Factor("b") * Factor("c") << "\n"; | |
std::cout << Factor("a") * (Factor("b") * Factor("c")) << "\n"; | |
std::cout << "\n"; | |
std::cout << product_left_prime(Factor("a"), Factor("b"), Factor("c")) << "\n"; | |
std::cout << product_right_prime(Factor("a"), Factor("b"), Factor("c")) << "\n"; | |
std::cout << "\n"; | |
std::cout << product_left(Factor("1"), Factor("a"), Factor("b"), Factor("c")) << "\n"; | |
std::cout << product_right(Factor("1"), Factor("a"), Factor("b"), Factor("c")) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment