Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code for my blog post on Higher Order Functions in C++.
#include <cassert>
#include <functional>
//
// Classical Function Definition
//
int add(int x, int y) {
return x + y;
}
int mul(int x, int y) {
return x * y;
}
//
// Function Objects
//
class Adder {
public:
int operator()(int x, int y) const {
return x + y;
}
};
class Multiplier {
public:
int operator()(int x, int y) const {
return x * y;
}
};
//
// Function Pointers
//
int resultOfCalculation_ptr(int (*op)(int, int), int x,
int y) {
return (*op)(x, y);
}
//
// std::function
//
int resultOfCalculation_fun(const std::function<int(int, int)>& op, int x,
int y) {
return op(x, y);
}
//
// Templates
//
template <typename FN>
int resultOfCalculation_tpl(const FN& op, int x, int y) {
return op(x, y);
}
int main() {
// Instantiate function objects
Adder add_o;
Multiplier mul_o;
// Define lambdas
auto add_l = [](int x, int y) { return x + y; };
auto mul_l = [](int x, int y) { return x * y; };
// Wrap in std::function
std::function<int(int, int)> add_f(add), add_of(add_o), add_lf(add_l),
mul_f(mul), mul_of(mul_o), mul_lf(mul_l);
// Check results
int x = 1,
y = 2,
s = 3,
p = 2;
assert(add(x, y) == s);
assert(add_o(x, y) == s);
assert(add_l(x, y) == s);
assert(mul(x, y) == p);
assert(mul_o(x, y) == p);
assert(mul_l(x, y) == p);
assert(add_f(x, y) == s);
assert(add_of(x, y) == s);
assert(add_lf(x, y) == s);
assert(mul_f(x, y) == p);
assert(mul_of(x, y) == p);
assert(mul_lf(x, y) == p);
assert(resultOfCalculation_ptr(add, x, y) == s);
assert(resultOfCalculation_ptr(mul, x, y) == p);
//assert(resultOfCalculation_ptr(add_o, x, y) == s);
//assert(resultOfCalculation_ptr(mul_o, x, y) == p);
assert(resultOfCalculation_ptr(add_l, x, y) == s);
assert(resultOfCalculation_ptr(mul_l, x, y) == p);
assert(resultOfCalculation_fun(add, x, y) == s);
assert(resultOfCalculation_fun(mul, x, y) == p);
assert(resultOfCalculation_fun(add_o, x, y) == s);
assert(resultOfCalculation_fun(mul_o, x, y) == p);
assert(resultOfCalculation_fun(add_l, x, y) == s);
assert(resultOfCalculation_fun(mul_l, x, y) == p);
assert(resultOfCalculation_tpl(add, x, y) == s);
assert(resultOfCalculation_tpl(mul, x, y) == p);
assert(resultOfCalculation_tpl(add_o, x, y) == s);
assert(resultOfCalculation_tpl(mul_o, x, y) == p);
assert(resultOfCalculation_tpl(add_l, x, y) == s);
assert(resultOfCalculation_tpl(mul_l, x, y) == p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment