open62541pp 0.18.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 IsConvertible : std::false_type {};
40
41template <typename T>
42struct IsConvertible<T, std::void_t<decltype(TypeConverter<T>{})>> : std::true_type {};
43
44template <typename T, typename = std::enable_if_t<detail::IsConvertible<T>::value>>
45[[nodiscard]] constexpr T fromNative(const typename TypeConverter<T>::NativeType& src) {
46 T dst{};
47 TypeConverter<T>::fromNative(src, dst);
48 return dst;
49}
50
51template <typename T, typename = std::enable_if_t<detail::IsConvertible<T>::value>>
52[[nodiscard]] constexpr auto toNative(const T& src) -> typename TypeConverter<T>::NativeType {
53 using NativeType = typename TypeConverter<T>::NativeType;
54 NativeType dst{};
55 TypeConverter<T>::toNative(src, dst);
56 return dst;
57}
58
59} // namespace detail
60
61} // namespace opcua
Type conversion from and to native types.