Due to the constraints of the domain I'm working with, I need to define string literals both as char const* and wchar const*, for example:
constexpr auto C_VAR_NAME_1 = "MY_VAR_NAME_1";
constexpr auto C_VAR_NAME_2 = "MY_VAR_NAME_2";
...
constexpr auto W_VAR_NAME_1 = L"MY_VAR_NAME_1";
constexpr auto W_VAR_NAME_2 = L"MY_VAR_NAME_2";
...
I have lots of constants and I'd like to avoid to define twice the same actual name of the variable (which could lead to some typo, hence unmatching names), so I've used some macro like this:
#define WTEXT_IMPL(name) L##name
#define WTEXT(name) WTEXT_IMPL(name)
#define MACRO_VAR_NAME_1 "MY_VAR_NAME_1"
#define MACRO_VAR_NAME_2 "MY_VAR_NAME_2"
...
constexpr auto C_VAR_NAME_1 = MACRO_VAR_NAME_1;
constexpr auto C_VAR_NAME_2 = MACRO_VAR_NAME_2;
...
constexpr auto W_VAR_NAME_1 = WTEXT(MACRO_VAR_NAME_1)
constexpr auto W_VAR_NAME_2 = WTEXT(MACRO_VAR_NAME_2)
...
This works but, if possible, I'd like to get rid of the macro stuff; so my question is: is it possible to achieve the same result at compile-time using plain C++ standard without macros? Thank you in advance for your help.
I would do this like that:
#include <string_view>
struct DoubleStringLiteral {
std::string_view str;
std::wstring_view wstr;
};
#define DOUBLE_LITERAL(name, value) \
constexpr DoubleStringLiteral name { \
value, \
L ## value \
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With