我想在编译时确定字符串是否包含特定字符。我以为我会用 std::string_view
因为它有 constexpr 方法来做我想做的事。这是代码:
#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";
}
由于这些错误,这不会编译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'
我已经做了很多谷歌搜索,但无法理解这个错误告诉我什么!我不明白变量在它的生命周期之外是如何被读取的,它是一个我认为在编译时可用的文字(不是吗?)。任何解释错误和如何修复的提示将不胜感激。谢谢。
最佳答案
你把事情复杂化了。 std::string_view
可以通过 const char*
build :
constexpr bool ContainsAsterisk(std::string_view view) {
// constexpr bool b = view.find('*') != view.npos; // ERROR
return view.find('*') != view.npos;
}
int main() {
constexpr bool b = ContainsAsterisk("123123*"); // OK
}
Why am I getting the error?
根据 cppreference , 一个函数可以是 constexpr ,如果:
there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression [...]
这意味着
constexpr
不是必需的。函数总是返回 constexpr
值,也不期望总是收到 constexpr
争论。它只确保对于某些特定的参数集(在这种情况下为 constexpr const char*
),它会给出 constexpr
返回值。因此,假设参数的定义总是
constexpr
(请参阅上面的错误行)无效。
关于c++ - 在编译时确定字符串是否包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65012853/