c++ - 在编译时确定字符串是否包含特定字符

标签 c++ visual-studio

我想在编译时确定字符串是否包含特定字符。我以为我会用 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/

相关文章:

c++ - 使用并行线程查找所有加起来等于给定数字的组合

c# - 通过 visual studio 运行的 UI 外观与安装的应用程序不同

c++ - Visual Studio 2013 C++ 变量监视不起作用

asp.net-mvc - 无法到达 Visual Studio 调试 "This site can'”

c++ - Const 变量随 C 中的指针改变

c++ - 如何使用 openGL 获得真正平滑的移动物体

带有 wxWidgets 的 C++,Unicode 与 ASCII,有什么区别?

c++ - Boost asio网络分离发送和接收

c++ - 使用鼠标滚轮时如何更新光标?

c# - Visual Studio 2013 调试崩溃