Skip to content

Commit 5e51cdd

Browse files
committed
🤙 Dynamic dispatch through closures in C++.
Today I realized that I, since closures are equivalent to a thunk, which can be used to simulate dynamic dispatch, it is possible to do dynamic dispatch in C++ without subclassing, and this is a very functional approach.
1 parent d006cf4 commit 5e51cdd

File tree

3 files changed

+47
-5
lines changed

3 files changed

+47
-5
lines changed

.github/workflows/format.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: Format
22
on: [push]
33
jobs:
44
format-cpp:
5-
name: 📀 Formatting
5+
name: 📀 Formatting C++
66
runs-on: ubuntu-latest
77
steps:
88
# Global part
@@ -11,17 +11,17 @@ jobs:
1111

1212
# C++ part
1313
- name: 🏗️ 🏃 clang-format
14-
uses: DoozyX/clang-format-lint-action@v0.17
14+
uses: DoozyX/clang-format-lint-action@v0.20
1515
with:
1616
source: ./cpp
1717
extensions: h,c,hpp,cpp
18-
clangFormatVersion: 17
18+
clangFormatVersion: 20
1919

2020
formta-py:
2121
defaults:
2222
run:
2323
working-directory: ./python
24-
name: 📀 Formatting
24+
name: 📀 Formatting Python
2525
runs-on: ubuntu-latest
2626
steps:
2727
- name: 🔔 Check out

cpp/polymorphism.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/// Copyright (c) RenChu Wang - All Rights Reserved
2+
3+
#include <functional>
4+
#include <iostream>
5+
#include <string>
6+
#include <vector>
7+
8+
struct A {
9+
int a;
10+
};
11+
12+
struct B {
13+
float b;
14+
};
15+
16+
struct C {
17+
std::string c;
18+
};
19+
20+
int main() {
21+
A a{899};
22+
B b{935};
23+
C c{"song"};
24+
25+
// Now I'm using closure to simulate a thunk,
26+
// which is a fat (function) pointer + data / state,
27+
// which can be used to implement dynamic dispatch (as in Go).
28+
std::function<int(int)> fa{[=](int num) { return a.a + num; }};
29+
30+
std::function<int(int)> fb{[=](int num) { return b.b * num; }};
31+
32+
std::function<int(int)> fc{[&](int num) { return int(c.c.size()) - num; }};
33+
34+
std::vector<std::function<int(int)>> funcs{fa, fb, fc};
35+
36+
// Dynamic dispatching.
37+
// This is very functional because this is similar to haskell's currying.
38+
// Each f is essentially a thunk in STG.
39+
for (auto&& f : funcs) {
40+
std::cout << f(1) << "\n";
41+
}
42+
}

python/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ authors = [
66
]
77
license = {text = "MIT"}
88
readme = "README.md"
9-
dynamic = ["version"]
9+
version = "0.0.0"
1010
requires-python = ">=3.13"
1111

1212
[build-system]

0 commit comments

Comments
 (0)