Reputation: 115
I have a single big template (loaded from file) in which I'm supposed to replace named arguments with their actual values. The issue is that I need to do it in two different functions, so part of the named arguments need to be substituted in func1()
and part - in func2()
.
The desired behavior is that the following below returns myarg1 myarg2
#include <iostream>
#include <string>
#include <fmt/core.h>
std::string func1(std::string& templ) {
return fmt::format(templ, fmt::arg("arg1", "myarg1"));
}
std::string func2(std::string& templ) {
return fmt::format(templ, fmt::arg("arg2", "myarg2"));
}
int main() {
std::string templ = "{arg1} {arg2}";
templ = func1(templ);
templ = func2(templ);
std::cout << templ << std::endl;
}
However I get
terminate called after throwing an instance of 'fmt::v6::format_error' what(): argument not found
inside the first function.
Is there a way to do partial/gradual arguments substitution in fmt
?
Upvotes: 2
Views: 1617
Reputation: 51
You can do it! You have to make sure that your {arg2}
survives func1
by escaping the brackets, e. g. {{arg2}}
#include <iostream>
#include <string>
#include <fmt/core.h>
std::string func1(std::string& templ) {
return fmt::format(templ, fmt::arg("arg1", "myarg1"));
}
std::string func2(std::string& templ) {
return fmt::format(templ, fmt::arg("arg2", "myarg2"));
}
int main() {
std::string templ = "{arg1} {{arg2}}";
templ = func1(templ);
templ = func2(templ);
std::cout << templ << std::endl;
}
Upvotes: 5