Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create strings depending on template arguments

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?

like image 854
cytrinox Avatar asked Nov 04 '10 19:11

cytrinox


People also ask

Does function template work with string?

The template function works for int and char, but not float and string.

Do template strings support multiline strings?

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.

What is templating literal templating strings?

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.

Can we pass Nontype parameters to 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.


1 Answers

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();
like image 161
Steve Jessop Avatar answered Oct 16 '22 16:10

Steve Jessop