cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

checking string-literal function argument at compile-time

Open Dharmesh946 opened this issue 7 months ago • 1 comments

Channel

C++Weekly

Topics

std::format("{}"); does not compiles while std::format("{}",1); does. How is it possible? (a look into std::format_string implementation, and especially its constructor? How function arguments seem to be usable in constant evaluated context?)

Length

Honestly don't know how much needs to be told...

Dharmesh946 avatar May 28 '25 13:05 Dharmesh946

The format string argument is a variadic template type that receives the types of the other passed parameters, and its constructor is consteval so it must run at compile time. From there it's usual constexpr/template metaprogramming to check the provided string against the given template arguments. The actual values of the other arguments can't be checked until runtime. There's a lot of different directions the video could take from there, it's rather open-ended.

LB-- avatar May 28 '25 20:05 LB--