xref: /openbmc/sdbusplus/include/sdbusplus/utility/consteval_string.hpp (revision d925c0bc5d0baa8702dcfcb5e11609e52ed7e86c)
1 #pragma once
2 
3 #include <algorithm>
4 #include <cstdint>
5 
6 namespace sdbusplus::utility
7 {
8 namespace details
9 {
10 
11 template <std::size_t N>
12 struct consteval_string_holder
13 {
14     char value[N] = {};
15 
consteval_string_holdersdbusplus::utility::details::consteval_string_holder16     consteval consteval_string_holder(const char (&str)[N])
17     {
18         std::ranges::copy(str, value);
19     }
20 };
21 
22 } // namespace details
23 
24 /** Type to allow compile-time parameter string comparisons.
25  *
26  *  Example:
27  *      void foo(consteval_string<"FOO">);
28  *
29  *  If the function is not called with foo("FOO"), it will be a compile error.
30  */
31 template <details::consteval_string_holder V>
32 struct consteval_string
33 {
34     std::string_view value;
35 
36     template <typename T>
consteval_stringsdbusplus::utility::consteval_string37     consteval consteval_string(const T& s) : value(s)
38     {
39         if (value != V.value)
40         {
41             report_error("String mismatch; check parameter name.");
42         }
43     }
44 
45     // This is not a real function but used to trigger compile errors due to
46     // calling a non-constexpr function in a constexpr context.
47     static void report_error(const char*);
48 };
49 
50 } // namespace sdbusplus::utility
51