open62541pp 0.17.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
typeconverter.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <type_traits>
4
5namespace opcua {
6
7/**
8 * Type conversion from and to native types.
9 *
10 * Native types can be both `UA_*` types and wrapper classes (like `UA_Guid` and `Guid`).
11 * The `TypeConverter` is mainly used within the `Variant` class to set/get non-native types.
12 *
13 * Template specializations can be added for conversions of arbitrary types:
14 * @code
15 * namespace ::opcua {
16 * template <>
17 * struct TypeConverter<MyCustomType> {
18 * using NativeType = Guid;
19 *
20 * static void fromNative(const NativeType& src, MyCustomType& dst) {
21 * // ...
22 * }
23 *
24 * static void toNative(const MyCustomType& src, NativeType& dst) {
25 * // ...
26 * }
27 * };
28 * }
29 * @endcode
30 */
31template <typename T, typename Enable = void>
33
34/* -------------------------------------- Traits and helper ------------------------------------- */
35
36namespace detail {
37
38template <typename T, typename = void>
39struct IsConvertibleType : std::false_type {};
40
41template <typename T>
42struct IsConvertibleType<T, std::void_t<decltype(TypeConverter<T>{})>> : std::true_type {};
43
44template <typename T>
45constexpr bool isConvertibleType = IsConvertibleType<T>::value;
46
47template <typename T, typename = std::enable_if_t<detail::isConvertibleType<T>>>
48[[nodiscard]] constexpr T fromNative(const typename TypeConverter<T>::NativeType& src) {
49 T dst{};
50 TypeConverter<T>::fromNative(src, dst);
51 return dst;
52}
53
54template <typename T, typename = std::enable_if_t<detail::isConvertibleType<T>>>
55[[nodiscard]] constexpr auto toNative(const T& src) -> typename TypeConverter<T>::NativeType {
56 using NativeType = typename TypeConverter<T>::NativeType;
57 NativeType dst{};
58 TypeConverter<T>::toNative(src, dst);
59 return dst;
60}
61
62} // namespace detail
63
64} // namespace opcua
Type conversion from and to native types.