非 static 的 constexpr 变量的地址在多次函数调用中可能会变,因此取地址的结果就不能是 constexpr 了。因此,你不能在 constexpr 变量里存储这样的地址……这会造成一个有意思的现象,虽然名义上是编译期分配的地址。但是我们只能在运行期观测到它的值。既然编译期获取不到它的值了,编译器在实现的时候其实只要给它分配一个符
非 static 的 constexpr 变量的地址在多次函数调用中可能会变,因此取地址的结果就不能是 constexpr 了...
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:...
std::string_view(C++17 起)。 复制 #include<array>constexpr std::array<int,3>arr={1,2,3};// std::array 是字面类型constexpr std::string_view sv="compile-time";// 合法,数据是编译期字面量// constexpr std::string_view sv2 = std::string("runtime"); // 错误:非编译期数据 1. 2...
constexpr extern std::string_view const s(“”); static_assert(s.empty()); // OK And if only extern is commented it succeeds, too: extern std::string_view const s; constexpr /extern/ std::string_view const s(“”); static_assert(s.empty()); // OKVisual...
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...
constexprstd::string_view msg ="Hello, world!"; 使用string_view之后就不会出现上面的顶层/底层const的坑了。所以在现代c++里能不用裸指针就尽量不要用。 参考 https://stackoverflow.com/questions/54258241/warning-iso-c-forbids-converting-a-string-constant-to-char-for-a-static-c...
此外,多个字符串对象可能使用重叠存储,因此两个指向字符串的指针相等也不意味着它们具有相同的值。
constexpr string_view sv{"hi"}; constexprpairpr{sv[0], sv[1]}; constexprarraya{pr.first, pr.second}; constexprintn1 = a[0]; constexprintn2 = a[1]; cout<< n1 <<' '<< n2 <<'\n'; } 编译器可以在编译期即决定 n1 和 n2 的数值;从最后结果的角度,上面程序就是输出了两个整数...
#include <string_view> #include <utility> enum class axis { x, y, z }; constexpr std::string_view axis_name(axis a) { // use static constexpr to avoid putting the table onto the stack static constexpr std::string_view names[] { "x", "y", "z" }; return names[std::to_...