xref: /openbmc/entity-manager/src/variant_visitors.hpp (revision 4e1142d6f418f48ea260132ebb5a4995b2310c90)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright 2019 Intel Corporation
3 
4 #pragma once
5 #include <stdexcept>
6 #include <string>
7 #include <variant>
8 
9 struct VariantToIntVisitor
10 {
11     template <typename T>
operator ()VariantToIntVisitor12     int operator()(const T& t) const
13     {
14         if constexpr (std::is_arithmetic_v<T>)
15         {
16             return static_cast<int>(t);
17         }
18         throw std::invalid_argument("Cannot translate type to int");
19     }
20 };
21 
22 struct VariantToStringVisitor
23 {
24     template <typename T>
operator ()VariantToStringVisitor25     std::string operator()(const T& t) const
26     {
27         if constexpr (std::is_same_v<T, std::string>)
28         {
29             return t;
30         }
31         else if constexpr (std::is_arithmetic_v<T>)
32         {
33             return std::to_string(t);
34         }
35         throw std::invalid_argument("Cannot translate type to string");
36     }
37 };
38