Skip to content

Instantly share code, notes, and snippets.

@farhangamary
Last active March 27, 2024 16:41
Show Gist options
  • Select an option

  • Save farhangamary/4b7a68963badb77a736abe1edcad92d0 to your computer and use it in GitHub Desktop.

Select an option

Save farhangamary/4b7a68963badb77a736abe1edcad92d0 to your computer and use it in GitHub Desktop.
A sample of meta and a sample of functional programming in c++
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
using namespace std;
int mod_by_six(int val);
int main()
{
vector<vector<int>> mtx = {
{112, 42, 83, 119},
{56, 125, 56, 49},
{15, 78, 101, 43},
{62, 98, 114, 108}};
function<vector<int>(vector<int>)> apply_mod = [](vector<int> vec)
{
transform(vec.begin(), vec.end(), vec.begin(), mod_by_six);
return vec;
};
auto rs = mtx | ranges::views::transform(apply_mod);
for (auto v : rs)
{
for (auto nv : v)
cout << nv << " ";
cout << endl;
}
return 0;
}
int mod_by_six(int val)
{
if (val % 6 == 0)
return 6;
else if (val % 2 == 0)
return 2;
else if (val % 3 == 0)
return 3;
else
return 0;
};
#include <iostream>
template <long int N>
struct MetaFactorial
{
enum
{
value = N * MetaFactorial<N - 1>::value
};
};
template <>
struct MetaFactorial<0>
{
enum
{
value = 1
};
};
int main()
{
std::cout << "Welcome to metaprogramming paradigm!" << std::endl
<< "Here everything is already calculated! and is ready for runtime." << std::endl
<< "It is the power of C++ templates, preprocessor macros, etc which"
<< " makes the C++ able to have metaprogramming paradigm." << std::endl
<< std::endl;
std::cout << "The Factorial(10): " << MetaFactorial<10>::value << std::endl;
std::cout << "The Factorial(13): " << MetaFactorial<13>::value << std::endl;
}
@farhangamary
Copy link
Author

$ g++ -o meta meta.cpp
$ ./meta
Welcome to metaprogramming paradigm!
Here everything is already calculated! and is ready for runtime.
It is the power of C++ templates, preprocessor macros, etc which makes the C++ able to have metaprogramming paradigm.

The Factorial(10): 3628800
The Factorial(13): 6227020800

@farhangamary
Copy link
Author

$ g++ -std=c++20 -o func functnl.cpp
$ ./func
2 6 0 0 
2 0 2 0 
3 6 0 0 
2 2 6 6 
$ 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment