Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string literals inside template which handles any char sizes

Tags:

c++

templates

Lets consider this kind of template:

template<typename CharT>
std::basic_string<CharT> refEnvVaraiable(const std::basic_string<CharT> &varaibleName)
{
    std::basic_string<CharT> result;
    result.reserve(varaibleName.length() + 3);
    result = "${" + varaibleName + "}";
    return result;
}

Plan is that this suppose to handle strings with any character size. This of course will not compile if argument function argument is std::wstring since there is no operator to concat it with string literal of type const char[].

How to force string literal to match desired character type? Do I have to provide specializations for constants representing literals (this lots of boiler plate code)? Or is there a ready tool for it?

Live sample

like image 204
Marek R Avatar asked Dec 07 '25 04:12

Marek R


1 Answers

One thing you can do is leverage if constexpr to code the different concatenations you want to support. When the code is compiled only the valid concatenation will get compiled and the rest will be discarded. That would give you something like

template<typename CharT>
std::basic_string<CharT> refEnvVaraiable(const std::basic_string<CharT> &varaibleName)
{
    std::basic_string<CharT> result;
    result.reserve(varaibleName.length() + 3);
    if constexpr (std::is_same_v<CharT, char>) result = "${" + varaibleName + "}";
    else if constexpr (std::is_same_v<CharT, wchar_t>) result = L"${" + varaibleName + L"}";
    else if constexpr (std::is_same_v<CharT, char16_t>) result = u"${" + varaibleName + u"}";
    else if constexpr (std::is_same_v<CharT, char32_t>) result = U"${" + varaibleName + U"}";
    else static_assert(false, "refEnvVaraiable called with unsupported character type");
    return result;
}
like image 88
NathanOliver Avatar answered Dec 08 '25 16:12

NathanOliver