I'd like to determine if a string contains a particular character at compile time. I thought I would use std::string_view
as it has constexpr methods to do what I want. This is the code:
#include <iostream>
#include <string_view>
using namespace std::literals;
template<std::size_t N>
constexpr bool ContainsAsterisk(const char(&formatString)[N])
{
constexpr std::string_view fmtString{ formatString, N - 1 }; // error C2131: expression did not evaluate to a constant
constexpr bool containsAsterisk = fmtString.find('*') != fmtString.npos;
return containsAsterisk;
}
int main()
{
if (ContainsAsterisk("sdf"))
{
std::cout << "sdf no\n";
}
if (ContainsAsterisk("er*r"))
{
std::cout << "er*r yes\n";
}
std::cout << "done\n";
}
This doesn't compile because of these errors
ConsoleApplication.cpp(9,41): error C2131: expression did not evaluate to a constant
ConsoleApplication.cpp(9,43): message : failure was caused by a read of a variable outside its lifetime
ConsoleApplication.cpp(9,43): message : see usage of 'formatString'
ConsoleApplication.cpp(17): message : see reference to function template instantiation 'bool ContainsAsterisk<4>(const char (&)[4])' being compiled
ConsoleApplication.cpp(10,37): error C2131: expression did not evaluate to a constant
ConsoleApplication.cpp(9,43): message : failure was caused by a read of a variable outside its lifetime
ConsoleApplication.cpp(9,43): message : see usage of 'formatString'
I've done quite a bit of googling, and can't understand what this error is telling me! I don't understand how the variable is being read outside it's lifetime, it's a literal (isn't it?) that I thought would be available at compile time.
Any tips explaining the error and how to fix would be appreciated. Thanks.
string_view
andfind
? Can you not simply just loop overformatString
?std::string_view
as the function parameter?