Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use a const char* or std::string variable containing grammar as argument to libfmt?

Hopefully this is a silly question. I have the following code:

#include <iostream>
#include <fmt/format.h>
#include <string>
int main(){
 double f = 1.23456789;
 std::cout << fmt::format( "Hello {:f} how are you?\n", f ) << "\n";
 return 0;
}

And this works as expected —Hello 1.234568 how are you?

But if I want to encapsulate the string passed into fmt::format as a variable, I run into a compiler error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
#include <fmt/format.h>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time
 std::cout << fmt::format( m, f ) << "\n";
 return 0;
}

However, on MSVC 2022 using #include <format>, this works perfectly…

#include <iostream>
//#include <fmt/format.h>
#include <format>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n";
 std::cout << std::format( m, f ) << "\n";
 return 0;
}

Is this possible using libfmt? It appears libfmt wants a constexpr value passed in whereas msvc’s <format> evaluates this at runtime. What silly mistake am I making here?

>Solution :

Since libfmt 8.1, you can wrap the format string in fmt::runtime to enable runtime formatting:

#include <iostream>
#include <fmt/format.h>
#include <string>
int main() {
 double f = 1.23456789;
 const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time
 std::cout << fmt::format(fmt::runtime(m), f ) << "\n";
 return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading