Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

c++ - Evaluating strlen at compilation time?

If my code has this constexpr string

constexpr char my_str[] = "hello";

the type of my_str contains information about its size, i.e. sizeof(my_str) is a constant 6, and can be used anywhere a constant is required.

What about strlen(my_str)? Can/should it also be evaluated to a compile-time constant?

Here is an example for yes: https://ideone.com/2U65bN

Here is an example for no: http://coliru.stacked-crooked.com/a/8cb094776dfc5969

What does the Standard say about this? Surely not "maybe"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C++17 you can use std::char_traits::length, which is constexpr, instead of strlen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...