如何声明constexpr C字符串? [英] How to declare constexpr C string?
问题描述
我想我很理解如何将关键字 constexpr
用于简单的变量类型,但是当涉及到指向值的指针时,我感到困惑。
I think i quite understand how to use the keyword constexpr
for simple variable types, but i'm confused when it comes to pointers to values.
我想声明一个constexpr C字符串文字,其行为类似于
I would like to declare a constexpr C string literal, which will behave like
#define my_str "hello"
这意味着编译器将C字符串文字插入到我输入此字符串的每个位置符号,我将可以在编译时使用sizeof获得它的长度。
That means the compiler inserts the C string literal into every place where i enter this symbol, and i will be able to get its length at compile-time with sizeof.
是 constexpr char * const my_str = hello ;
或 const char * constexpr my_str = hello;
或 constexpr char my_str [] = hello;
还是其他东西?
推荐答案
是
constexpr char * const my_str = hello;
否,因为字符串文字不能转换为指向<$ c的指针$ c> char 。 (它曾经是C ++ 11之前的版本,但即使这样,该转换也已被弃用。)
No, because a string literal is not convertible to a pointer to char
. (It used to be prior to C++11, but even then the conversion was deprecated).
或
const char * constexpr my_str = hello;
否。 constexpr
不能去那里。
这会很好地构成:
constexpr const char * my_str = "hello";
但它不能满足以下条件:
but it does not satify this:
这样我就可以在编译时使用sizeof等获取其长度。
So that i will be able to get its length at compile-time with sizeof, etc.
或
constexpr char my_str [] = hello;
这是格式正确的,确实可以在编译时使用 sizeof
来获取长度。请注意,此大小是数组的大小,而不是字符串的长度,即该大小包括空终止符。
This is well formed, and you can indeed get the length at compile time with sizeof
. Note that this size is the size of the array, not the length of the string i.e. the size includes the null terminator.
这篇关于如何声明constexpr C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!