如何声明 constexpr C 字符串?

How to declare constexpr C string?

我想我很明白如何将关键字 constexpr 用于简单的变量类型,但是当涉及到指向值的指针时我感到困惑。

我想声明一个 constexpr C 字符串文字,其行为类似于

#define my_str "hello"

这意味着编译器将 C 字符串文字插入到我输入该符号的每个地方,并且我将能够在编译时使用 sizeof 获取它的长度。

是吗constexpr char * const my_str = "hello";

const char * constexpr my_str = "hello";

constexpr char my_str [] = "hello";

或者其他不同的东西?

C++17, you can use std::string_view and string_view_literals

using namespace std::string_view_literals;
constexpr std::string_view my_str = "hello, world"sv;

然后,

my_str.size() 是编译时间常数。

Is it constexpr char * const my_str = "hello";

不,因为字符串文字不能转换为 指向 char 的指针。 (它曾经是 C++11 之前的版本,但即便如此,转换也已被弃用)。

or const char * constexpr my_str = "hello";

没有。 constexpr去不了

这将是合式的:

constexpr const char * my_str = "hello";

但它不满足这个:

So that i will be able to get its length at compile-time with sizeof, etc.


or constexpr char my_str [] = "hello";

这个格式很好,你确实可以在编译时用sizeof得到长度。请注意,此大小是数组的大小,而不是字符串的长度,即大小包括空终止符。