I have many classes/methods like this:
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
struct Foo
{
std::basic_string<CharT, TraitsT> getFoo(void) const
{
return "Foo"; // + this->member_var1 + this->member_var2...
}
};
But depending on CharT, I have to use "", L"", u"" or "U" (for char, wchar_t, u16char_t, u32char_t).
What syntax must be used to create strings that are independed from such template arguments?
The template function works for int and char, but not float and string.
Template Strings significantly simplify multiline strings. Simply include newlines where they are needed and BOOM. Here's an example: Any whitespace inside of the backtick syntax will also be considered part of the string.
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
Do you really need the different literals, or can you use the iterator constructor?
const char *f = "Foo";
return std::basic_string<CharT, TraitsT>(f, f + 3);
Maybe with something a bit more robust than "3" in there, if you're worried about ease of changing the literal in future.
In response to the point that this isn't very nice, what about:
template <typename CharT, typename TraitsT, size_t N>
basic_string<CharT, TraitsT> proper_string(const char (&src)[N]) {
return basic_string<CharT, TraitsT>(src, src+N-1);
}
Then you have:
return proper_string<CharT, TraitsT>("Foo");
If you really need the different literal, then the only thing I've thought of so far is to create traits for it, which is really horrible:
template<typename T> struct FooString {
};
template<> struct FooString<char> {
static const char *value() { return "Foo"; }
};
template<> struct FooString<wchar_t> {
static const wchar_t *value() { return L"Foo"; }
};
... etc ...
return FooString<CharT>::value();
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