虽然不能直接使用std::string与constexpr结合,但可以使用字符串字面量(即const char[])与constexpr结合来声明编译时常量字符串。示例如下: cpp constexpr char myString[] = "Hello, constexpr!"; 这里,myString是一个字符数组,使用constexpr声明,表示它在编译时期就确定了内容,并且不能修改。
从GCC 9.1.0 开始不支持,以下编译失败: #include <string> int main() { constexpr std::string s("abc"); } 和: g++-9 -std=c++2a main.cpp 有错误: error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not litera...
import <iostream>; import <string_view>; import my_string; static constexpr std::string_view hello_world{"Hello World at compilation (outside module)"}; int main(){ std::cout << hello_world << std::endl; std::cout << my_string::MyString::string_at_runtime << std::endl; std:...
自从C++20起,std::string是一个constexpr类。其中: sso长度内的std::string在栈上local分配内存。sso...
constexpr、动态内存分配、vector 和 string C++ 一直在拓展constexpr的能力。在C++20之前constexpr函数的限制很大,比如: 无法进行动态内存分配(new/delete)。 无法使用std::vector和std::string等常用容器。 C++20 往前迈进了一大步,constexpr函数可以进行有限制的动态内存分配和std::vector/std::string的使用。比如...
}intmain(){conststring message ="Hello, world!";printMessage(message);return0; } 示例2:constexpr 代码语言:C++ 代码运行次数:0 自动换行 运行 AI代码解释 #include<iostream>usingnamespacestd;constexprintsquare(intx){returnx * x; }intmain(){constexprintnum =5;constexprintresult =square(num)...
std::string在有适当支持的情况下应该是constexpr的,以便在编译时评估字符串操作,但它似乎并非如此。 我误解了标准库中__cpp_lib_constexpr_string宏的效用。 C++20 将在constexpr上下文中提供更多文本操作的灵活性。 我已经做了功课,发现了 Stack Overflow 上关于类似问题或如何在constexpr上下文中使用std::string...
conststd::string A::name("aaa"); 一个特例是,如果static常量的类型是内置的整数类型,如char、int、size_t等,那么可以在类中直接给出初始值,且不需要在类外再进行定义了。编译器会将这种static常量直接替换为相应的初始值,相当于宏替换。但如果在代码中我们像正常变量那样使用这个static常量,如取它的地址,而...
constexpr std::string_view foo("abc"); // C2131: expression did not evaluate to a constant constexpr std::string_view foo("abc", 3); // No error Looking deeper into the code, the root of the problem seems to be that the std::char_traits::length() function is...
如果是将std::string,换成std::string_view则又是正确的: constexprstd::string_viewhello="Hello World!";//Right!//constexpr auto hello = "Hello World!"sv; string_view是C++17所提供的用于处理只读字符串的轻量对象。我们通过constexpr修饰的构造函数: ...