Handling string literals

Started by
10 comments, last by Bearhugger 8 years, 3 months ago

Don't reinvent yet another string class.

Now, let him do it. Writing my own string class taught me a lot about C++ programming early on. Its a good exercise.

Advertisement

I don't believe you can tell whether a string was given as a literal or as a variable, but it would be trivial if the following were legal C++.


constexpr bool is_literal_string(const char* p)
{
    return p[0] == p[0];
}

bool is_literal_string(const char*)
{
    return false;
}

If you have a string literal, the compiler is able to use the constexpr version, would pick it, and the function returns true. If you pass in a variable then it's unable to run the constexpr version, so it generates a call to the non-constexpr version, which always returns false. (And would likely be optimized away.)

The problem with the code above is that you can't overload function with an identical (but constexpr) version. I figure that would make function overload resolution even more complex than it already is.

This topic is closed to new replies.

Advertisement