2

Is there a way to use fmt with a spec that is computed at runtime.

Noticed that with gcc 10 this code worked fine but not with modern gcc.

#include <fmt/format.h>
const char* get_spec(bool test)
{ // image this is implemented in some other .cpp file
 return test ? "->{}" : "{}<-";
}
int main() {
 const char* non_constexpr = get_spec(true);
 fmt::print(non_constexpr,1);
}

https://godbolt.org/z/oh9n3cEnT

asked Jun 11, 2023 at 6:35
6
  • Supply -> and <- as strings. fmt::print("{}{}{}", (test ? "->" : ""), 1, (test ? "" : "<-")); Commented Jun 11, 2023 at 6:41
  • @user7860670 Sure but would like to get the format strings at runtime, or from some library in another translation unit. Commented Jun 11, 2023 at 6:42
  • Amount and types of the arguments passed are fixed at comiple-time therefore format string compatibility should be checked at compile-time as well. Commented Jun 11, 2023 at 6:44
  • There's a bunch of similar duplicated questions on SO. Commented Jun 11, 2023 at 6:44
  • 1
    Same issue with std::format, by the way... Commented Jun 11, 2023 at 6:44

2 Answers 2

4

You need to use fmt::runtime():

#include <fmt/format.h>
const char* get_spec(bool test)
{ // image this is implemented in some other .cpp file
 return test ? "->{}" : "{}<-";
}
int main() {
 const char* non_constexpr = get_spec(true);
 fmt::print(fmt::runtime(non_constexpr),1);
}

Like always, gcc has bad error descriptions. The problem is that the normal constructor for format patterns is consteval in C++20, so you cannot pass a runtime format to it.

For that purpose, just use fmt::runtime() around your runtime format pattern.

In case of C++20's std::format problem, you need to use std::vformat to resolve the problem as mentioned in cpp ref.

answered Jun 11, 2023 at 6:54
Sign up to request clarification or add additional context in comments.

Comments

1

You can use fmt::vprint (std::vprint_unicode in C++23) for runtime format string

const char* non_constexpr = get_spec(true);
int arg = 1;
fmt::vprint(non_constexpr, fmt::make_format_args(arg));
answered Jun 11, 2023 at 7:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.