C++ fmt 库。部分参数替换
C++ fmt lib. Partial arguments substitution
我有一个大模板(从文件加载),我应该在其中用实际值替换命名参数。问题是我需要在两个不同的函数中执行此操作,因此需要在 func1()
中替换部分命名参数,在 func2()
.
中替换部分 -
期望的行为是以下 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;
}
不过我得到
terminate called after throwing an instance of 'fmt::v6::format_error' what(): argument not found
在第一个函数中。
有没有办法在 fmt
中进行 partial/gradual 参数替换?
不,{fmt} 要求在一次调用中传递所有参数。
你可以的!您必须通过转义括号确保您的 {arg2}
存活 func1
,例如。 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;
}
我有一个大模板(从文件加载),我应该在其中用实际值替换命名参数。问题是我需要在两个不同的函数中执行此操作,因此需要在 func1()
中替换部分命名参数,在 func2()
.
期望的行为是以下 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;
}
不过我得到
terminate called after throwing an instance of 'fmt::v6::format_error' what(): argument not found
在第一个函数中。
有没有办法在 fmt
中进行 partial/gradual 参数替换?
不,{fmt} 要求在一次调用中传递所有参数。
你可以的!您必须通过转义括号确保您的 {arg2}
存活 func1
,例如。 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;
}