Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW
Last active May 3, 2022 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW/4c36fd85f412a31f8c0aa86f39c52191 to your computer and use it in GitHub Desktop.
Save Hermann-SW/4c36fd85f412a31f8c0aa86f39c52191 to your computer and use it in GitHub Desktop.
Self contained test code for partial initializing struct function pointers with lambdas (c++14)
// Copyright: https://mit-license.org/
//
// cpplint lmbda.cpp 2>&1 | grep -v "Is this a non-const reference?"
// g++ -Wall -Wextra -pedantic -std=c++14 -g lmbda.cpp -o lmbda
//
#include <assert.h>
#include <iostream>
#include <vector>
#include <functional>
typedef int num;
typedef num vertex;
typedef num edge;
typedef std::vector<edge> Vertex;
typedef std::vector<std::vector<num>> Edge;
#define _f(g) if (g) g
struct compact5_traversal_visitor {
std::function<void()> begin_traversal = 0;
std::function<std::vector<int>()> end_traversal = 0;
std::function<void(vertex)> begin_vertex = 0;
std::function<void(vertex)> end_vertex = 0;
std::function<void(edge)> next_edge = 0;
std::function<void(vertex, edge)> next_vertex_edge = 0;
};
class graph {
public:
std::vector<Vertex> V;
std::vector<Edge> E;
explicit graph(num n = 0, num m = 0) {
Vertex v = {};
Edge e = {};
V = std::vector<Vertex>(n, v);
E = std::vector<Edge>(m, e);
}
};
std::vector<int> compact5_traversal(graph& G, compact5_traversal_visitor c5v) {
if (!c5v.end_traversal) {
c5v.end_traversal = []() { return std::vector<int>(0); };
}
_f(c5v.begin_traversal)();
_f(c5v.begin_vertex)(G.V.size()-1);
return c5v.end_traversal();
}
int main() {
graph G(3);
compact5_traversal(G, {
[G]() { std::cout << "begin_traversal " << G.V.size() << std::endl; },
[&G]() { std::cout << "end_traversal " << G.V.size() << std::endl;
return std::vector<int>(0); },
[&G](vertex v) { std::cout << v << std::endl;
G.V.push_back(std::vector<edge>(0)); }
});
return 0;
}
@Hermann-SW
Copy link
Author

Hermann-SW commented May 3, 2022

Corrected 1st version by advice from older son to use "std::function".
Now compile warning from before is gone, and it just works with locally defined graph G:
https://forums.raspberrypi.com/viewtopic.php?p=1999519#p1999519

pi@pi400-64:~ $ g++ -Wall -Wextra -pedantic -std=c++14 -g lmbda.cpp -o lmbda
pi@pi400-64:~ $ ./lmbda 
begin_traversal 3
2
end_traversal 4
pi@pi400-64:~ $ 

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