blob: 60119bec6fefaf3cd7680db15579788e5028fee7 [file] [log] [blame]
Brad Bishop65ffffa2016-11-29 12:31:31 -05001#pragma once
2
3namespace phosphor
4{
5namespace inventory
6{
7namespace manager
8{
Brad Bishop9bbfcb12017-02-04 10:51:06 -05009/** @struct MakeVariantVisitor
10 * @brief Return a variant if the visited type is a possible variant type.
11 *
12 * @tparam V - The desired variant type.
13 */
14template <typename V>
15struct MakeVariantVisitor
16{
17 /** @struct Make
18 * @brief Return variant visitor.
19 *
20 * @tparam T - The variant type to return.
21 * @tparam Arg - The type being visited in the source variant.
22 * @tparam Enable - Overload resolution removal.
23 */
24 template <typename T, typename Arg, typename Enable = void>
25 struct Make
26 {
27 static auto make(Arg&& arg)
28 {
29 throw sdbusplus::message::variant_ns::bad_variant_access(
30 "in MakeVariantVisitor");
31 return T();
32 }
33 };
Brad Bishop65ffffa2016-11-29 12:31:31 -050034
Brad Bishop9bbfcb12017-02-04 10:51:06 -050035 /** @struct Make
36 * @brief Return variant visitor.
37 *
38 * struct Make specialization if Arg is in T (int -> variant<int, char>).
39 */
40 template <typename T, typename Arg>
41 struct Make<T, Arg,
42 typename std::enable_if<std::is_convertible<Arg, T>::value>::type>
43 {
44 static auto make(Arg&& arg)
45 {
46 return T(std::forward<Arg>(arg));
47 }
48 };
49
50 /** @brief Make variant visitor. */
51 template <typename Arg>
52 auto operator()(Arg&& arg) const
53 {
54 return Make<V, Arg>::make(arg);
55 }
56};
57
58/** @brief Convert variants with different contained types.
59 *
60 * @tparam V - The desired variant type.
61 * @tparam Arg - The source variant type.
62 *
63 * @param[in] v - The source variant.
64 * @returns - The converted variant.
65 */
66template <typename V, typename Arg>
67auto convertVariant(Arg&& v)
68{
69 return sdbusplus::message::variant_ns::apply_visitor(
70 MakeVariantVisitor<V>(), v);
71}
Brad Bishop65ffffa2016-11-29 12:31:31 -050072} // namespace manager
73} // namespace inventory
74} // namespace phosphor
75
76// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4