algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
broker_list.hpp
1#pragma once
2
3#include "./broker_traits.hpp"
4
5#include <cstddef>
6#include <optional>
7#include <string_view>
8#include <type_traits>
9
10namespace algotradelib {
11
13template <typename T>
14struct type_tag {
16 using type = T;
17};
18
20template <typename... Clients>
21struct type_list {
23 static constexpr std::size_t size = sizeof...(Clients);
24};
25
26namespace port_detail {
27
28template <typename List>
29struct is_type_list : std::false_type {};
30
31template <typename First, typename... Rest>
32struct is_type_list<type_list<First, Rest...>> : std::true_type {};
33
34// Whether no two clients share `BrokerTraits<Client>::name`.
35template <typename... Clients>
36constexpr bool distinct_names() {
37 const std::string_view names[] = {BrokerTraits<Clients>::name...};
38 for (std::size_t i = 0; i < sizeof...(Clients); ++i) {
39 for (std::size_t j = i + 1; j < sizeof...(Clients); ++j) {
40 if (names[i] == names[j]) {
41 return false;
42 }
43 }
44 }
45 return true;
46}
47
48template <typename Visit, typename First, typename... Clients>
49auto visit_named(type_list<First, Clients...>, std::string_view name, Visit& visit) {
50 using R = std::invoke_result_t<Visit&, type_tag<First>>;
51 static_assert(
52 (std::is_same_v<R, std::invoke_result_t<Visit&, type_tag<Clients>>> && ...),
53 "with_broker: visit must return the same type for every client"
54 );
55 static_assert(
56 !std::is_void_v<R> && !std::is_reference_v<R>, "with_broker: visit must return a value, not void or a reference"
57 );
58 static_assert(
59 distinct_names<First, Clients...>(),
60 "with_broker: listed clients need distinct names; a broker's asynchronous and blocking clients share one"
61 );
62 std::optional<R> result;
63 const auto match = [&](auto tag) {
64 return name == BrokerTraits<typename decltype(tag)::type>::name &&
65 (static_cast<void>(result.emplace(visit(tag))), true);
66 };
67 static_cast<void>((match(type_tag<First>{}) || ... || match(type_tag<Clients>{})));
68 return result;
69}
70
71} // namespace port_detail
72
85template <typename List, typename Visit>
86auto with_broker(std::string_view name, Visit&& visit) {
87 static_assert(port_detail::is_type_list<List>::value, "with_broker: List must be a non-empty type_list");
88 return port_detail::visit_named(List{}, name, visit);
89}
90
91} // namespace algotradelib
The library: broker-neutral types (core), and the modules below.
auto with_broker(std::string_view name, Visit &&visit)
Calls visit with the type_tag of the client in List whose BrokerTraits<Client>::name is name.
A compile-time list of broker client types, for with_broker.
A type carried as a value, so a C++17 visitor can be called with a type.