【问题标题】:C++ fmt lib. Partial arguments substitutionC++ fmt 库。部分参数替换
【发布时间】:2021-06-05 12:09:53
【问题描述】:

我有一个大模板(从文件加载),我应该用它们的实际值替换命名参数。问题是我需要在两个不同的函数中执行此操作,因此部分命名参数需要替换为 func1() 和部分 - 替换为 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 中进行部分/渐进的参数替换?

【问题讨论】:

  • fmt::format 不是搜索和替换功能。您使用了错误的库。

标签: c++ fmt


【解决方案1】:

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

【讨论】:

  • 谢谢!尽管如此,伟大的库。
【解决方案2】:

你可以的!您必须通过转义括号来确保您的{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;
}

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 2021-09-10
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多