Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining string literal constants once both as char const* and wchar const*

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.

like image 222
Stefano Bellotti Avatar asked Nov 22 '19 09:11

Stefano Bellotti


1 Answers

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

like image 169
Marek R Avatar answered Oct 19 '22 15:10

Marek R