How to declare constexpr C string?

烂漫一生 提交于 2019-12-08 15:54:07

问题


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.

I would like to declare a constexpr C string literal, which will behave like

#define my_str "hello"

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.

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

or const char * constexpr my_str = "hello";

or constexpr char my_str [] = "hello";

or something yet different?


回答1:


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

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).

or const char * constexpr my_str = "hello";

No. constexpr cannot go there.

This would be well formed:

constexpr const char * my_str = "hello";

but it does not satify this:

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


or constexpr char my_str [] = "hello";

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.




回答2:


In 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;

Then,

my_str.size() is compile time constant.



来源:https://stackoverflow.com/questions/46100310/how-to-declare-constexpr-c-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!