-
Notifications
You must be signed in to change notification settings - Fork 5
/
08 - type erasure with boost.typeerasure #1.cpp
44 lines (36 loc) · 1.12 KB
/
08 - type erasure with boost.typeerasure #1.cpp
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 <boost/type_erasure/any.hpp>
#include <boost/type_erasure/member.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <string>
#include <functional>
#include <iostream>
using namespace std::literals;
struct TCPConnection {
void send(const char *s) { std::cout << "TCP: " << s << '\n'; }
};
struct UDPConnection {
void send(const char *s) { std::cout << "UDP: " << s << '\n'; }
};
struct TCPConnectionFactory {
TCPConnection operator()() { return TCPConnection(); }
};
struct UDPConnectionFactory {
UDPConnection operator()() { return UDPConnection(); }
};
template <class ConnectionFactory>
void send(ConnectionFactory &conFactory) {
auto con = conFactory();
con.send("Hello");
}
BOOST_TYPE_ERASURE_MEMBER((has_send), send)
using Connection = boost::type_erasure::any<boost::mpl::vector<has_send<void(const char*)>, boost::type_erasure::copy_constructible<>>>;
int main(int argc, char *argv[]) {
std::function<Connection()> factory;
if (argc > 1 && argv[1] == "tcp"s) {
factory = TCPConnectionFactory();
}
else {
factory = UDPConnectionFactory();
}
send(factory);
}