1

我有一个大模板(从文件加载),我应该用它们的实际值替换命名参数。问题是我需要在两个不同的函数中执行此操作,因此需要将部分命名参数替换为 infunc1()和 part-in func2()

期望的行为是以下返回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

4

2 回答 2

2

你能行的!您必须通过转义括号来确保您的{arg2}生存,例如func1{{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;
}
于 2021-11-19T14:38:29.533 回答
1

不,{fmt} 要求在一次调用中传递所有参数。

于 2021-03-08T14:33:55.947 回答