1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 
17 #pragma once
18 #include <boost/type_index.hpp>
19 
20 #include <stdexcept>
21 #include <string>
22 #include <variant>
23 
24 namespace details
25 {
26 
27 template <typename U>
28 struct VariantToNumericVisitor
29 {
30     template <typename T>
operator ()details::VariantToNumericVisitor31     U operator()(const T& t) const
32     {
33         if constexpr (std::is_arithmetic_v<T>)
34         {
35             return static_cast<U>(t);
36         }
37         throw std::invalid_argument(
38             "Cannot translate type " +
39             boost::typeindex::type_id<T>().pretty_name() + " to " +
40             boost::typeindex::type_id<U>().pretty_name());
41     }
42 };
43 
44 } // namespace details
45 
46 using VariantToFloatVisitor = details::VariantToNumericVisitor<float>;
47 using VariantToIntVisitor = details::VariantToNumericVisitor<int>;
48 using VariantToUnsignedIntVisitor =
49     details::VariantToNumericVisitor<unsigned int>;
50 using VariantToDoubleVisitor = details::VariantToNumericVisitor<double>;
51 
52 struct VariantToStringVisitor
53 {
54     template <typename T>
operator ()VariantToStringVisitor55     std::string operator()(const T& t) const
56     {
57         if constexpr (std::is_same_v<T, std::string>)
58         {
59             return t;
60         }
61         else if constexpr (std::is_arithmetic_v<T>)
62         {
63             return std::to_string(t);
64         }
65         throw std::invalid_argument(
66             "Cannot translate type " +
67             boost::typeindex::type_id<T>().pretty_name() + " to string");
68     }
69 };
70