-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path07 - type erasure with std-function.cpp
More file actions
44 lines (36 loc) · 1.04 KB
/
07 - type erasure with std-function.cpp
File metadata and controls
44 lines (36 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <string>
#include <memory>
#include <functional>
#include <iostream>
using namespace std::literals;
struct Connection {
virtual ~Connection() = default;
virtual void send(const char*) = 0;
};
struct TCPConnection : public Connection {
void send(const char *s) { std::cout << "TCP: " << s << '\n'; }
};
struct UDPConnection : public Connection {
void send(const char *s) { std::cout << "UDP: " << s << '\n'; }
};
struct TCPConnectionFactory {
std::unique_ptr<Connection> operator()() { return std::unique_ptr<Connection>(new TCPConnection); }
};
struct UDPConnectionFactory {
std::unique_ptr<Connection> operator()() { return std::unique_ptr<Connection>(new UDPConnection); }
};
template <class ConnectionFactory>
void send(ConnectionFactory &conFactory) {
auto con = conFactory();
con->send("Hello");
}
int main(int argc, char *argv[]) {
std::function<std::unique_ptr<Connection>()> factory;
if (argc > 1 && argv[1] == "tcp"s) {
factory = TCPConnectionFactory();
}
else {
factory = UDPConnectionFactory();
}
send(factory);
}