opynsim
Unofficial C++ Documentation
Loading...
Searching...
No Matches
conversion.h
Go to the documentation of this file.
1#pragma once
2
3#include <concepts>
4#include <utility>
5
6namespace osc
7{
8 // `Converter<T, U>` is a standardized API for explicitly converting `T` to `U`.
9 //
10 // It is designed similarly to `std::hash<Key>`, where the intent is to make it possible
11 // to uniformly define additional conversions between types that the developer may not
12 // have control over (e.g. library types). The `Converter<T, U>` is chosen based on
13 // C++'s template specialization semantics:
14 //
15 // - If a template specialization of `Converter<T, U>` is available, it is used.
16 //
17 // - Otherwise, a default implementation is provided which, assuming `t` is a universal
18 // reference of type `T&&`, calls `static_cast<U>(std::forward<T>(value))`.
19 //
20 // Each program- or user-provided specialization of `Converter` should define a `operator()`
21 // member function(s) that are capable of returning an instance of `U` given a `T`, e.g.:
22 //
23 // typename<>
24 // struct osc::Converter<A, B> final {
25 // U operator()(T) const;
26 // U operator()(const T&) const;
27 // U operator()(T&&) const;
28 // };
29 template<typename T, typename U>
30 struct Converter;
31
32 // Default `Converter` implementation
33 template<typename T, typename U>
34 requires std::constructible_from<U, T>
35 struct Converter<T, U> final {
36
37 template<typename TVal>
38 requires std::same_as<std::remove_cvref_t<TVal>, std::remove_cvref_t<T>>
39 U operator()(TVal&& value) const
40 {
41 return static_cast<U>(std::forward<TVal>(value));
42 }
43 };
44
45 // internal detail
46 namespace detail
47 {
48 // Satisfied if `Converter<T, U>` can be instantiated by the compiler
49 template<typename T, typename U>
50 concept HasConverter = requires { { Converter<T, U>{} }; };
51 }
52
53 // a helper method that converts the provided `T` to a (potentially, qualified value/ref) `U` using a `Converter<T, U>`
54 template<typename U, typename T>
56 constexpr U to(T&& value)
57 {
58 return Converter<std::remove_cvref_t<T>, U>{}(std::forward<T>(value));
59 }
60}
Definition conversion.h:50
Definition custom_decoration_generator.h:5
constexpr U to(T &&value)
Definition conversion.h:56
U operator()(TVal &&value) const
Definition conversion.h:39
Definition conversion.h:30