我对于constexpr
编程比较陌生,正在尝试在constexpr
上下文中进行一些基本的string_view
对象操作。在我的情况下,所有字符串最初都是源代码中的字面值,因此它们应该是常量表达式。我发现我可以从一个字符串字面量构造一个constexpr string_view
而没有任何问题。
但是,如果我尝试调用带有字符串字面量的string_view
参数的constexpr
函数,那么编译会失败。请参见以下示例(Compiler Explorer链接):
#include <string_view>
// this doesn't compile; the compiler complains that `sv` is not a constant-expression
constexpr bool foo(std::string_view sv)
{
constexpr auto it = sv.find('b');
return it != sv.end();
}
// this compiles just fine, though
constexpr std::string_view bar("def");
int main()
{
foo("abc");
}
gcc 8.3 提供以下错误:
<source>: In function 'constexpr bool foo(std::string_view)':
<source>:5:32: in 'constexpr' expansion of 'sv.std::basic_string_view<char>::find(((int)'b'), 0)'
<source>:5:36: error: 'sv' is not a constant expression
constexpr auto it = sv.find('b');
为什么将
foo()
的 string_view
参数不视为常量表达式?
basic_string_view::find
是constexpr
的。 - Nathan Piersonconstexpr
https://godbolt.org/z/TKMxn8 - Marek Rfoo
时无法评估sv.find('b');
,因为在编译foo
时未知sv
的值。另一方面,当调用foo(bar);
时可以在编译时进行评估,因为在这种情况下,foo
的参数是已知的。 - Marek R