lhog
lhog

Reputation: 115

C++ fmt lib. Partial arguments substitution

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

Answers (2)

thorwyn
thorwyn

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

vitaut
vitaut

Reputation: 55594

No, {fmt} requires all arguments to be passed in one call.

Upvotes: 1

Related Questions