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
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;
}
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