Read about the user defined literals, and find it somehow obscure about defining a string literal overload from char[]
.
The definitely correct way is like this
std::string operator "" _s (const char* m, std::size_t)
{
return std::string(m);
}
int main()
{
std::string r = "hello,"_s + " world"_s;
return 0;
}
But in fact the type of something like "hello"
is const char (&)[N]
(where N
is the length). So I wonder if there is an alternative approach like this
template <std::size_t N>
std::string operator "" _s (const char (&m)[N])
{
return std::string(m);
}
But oops the compiler (g++4.8 in Ubuntu 14.04) gave me an error
‘std::string operator"" _s(const char (&)[N])’ has invalid argument list
std::string operator "" _s (char const (&m)[N])
^
Then I tried to remove the unused std::size_t
parameter from the correct way (std::string operator "" _s (const char* m)
) but got the error
unable to find string literal operator ‘operator"" _s’ with ‘const char [7]’, ‘long unsigned int’ arguments
std::string r = "hello,"_s + " world"_s;
So is that mandatory to have the length as a parameter when the primary literal is a char[]
or a wchar_t[]
?