I have the following code:
constexpr uint32_t countWords(const char* str) {
constexpr std::size_t length = std::char_traits<char>::length(str);
std::uint32_t count = 0;
for (std::size_t i = 0; i < length; i++) {
if (str[i] == ' ') {
count++;
}
}
return count;
}
My problem arises on the first line of the function where I get a syntax error stating that:
str cannot be used as a constant
when I try to pass it to std::char_traits<char>::length
. If I remove the constexpr from the length
variable the error goes away, but to me that implies that the variable is not obtainable at compile time which defeats the purpose of the constexpr function. I plant call this functions using string literals as the parameter.