Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for dynamic arg sets #819

Merged
merged 3 commits into from
Jul 21, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,16 @@ class basic_format_args {
set_data(store.data_);
}

/**
\rst
Constructs a `basic_format_args` object from a dynamic set of arguments.
\endrst
*/
basic_format_args(const format_arg *args, size_type count)
: types_(-static_cast<int64_t>(count)) {
set_data(args);
}

/** Returns the argument at specified index. */
format_arg get(size_type index) const {
format_arg arg = do_get(index);
Expand Down
11 changes: 11 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1308,6 +1308,17 @@ TEST(FormatTest, Variadic) {
EXPECT_EQ(L"abc1", format(L"{}c{}", L"ab", 1));
}

TEST(FormatTest, Dynamic) {
using ctx = fmt::format_context;
std::vector<fmt::basic_format_arg<ctx>> args;
args.emplace_back(fmt::internal::make_arg<ctx>(42));
args.emplace_back(fmt::internal::make_arg<ctx>("abc1"));
args.emplace_back(fmt::internal::make_arg<ctx>(1.2f));

std::string result = fmt::vformat("{} and {} and {}", fmt::basic_format_args<ctx>(args.data(), (unsigned)args.size()));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the cast is necessary here. Also please restring the line width to 80 chars.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cast is necessary; the size is being truncated. On MSVC for example:
warning C4267: 'argument': conversion from 'size_t' to 'fmt::v5::basic_format_args<fmt::v5::format_context>::size_type', possible loss of data

I can change it to a static_cast if that makes you happier.

EXPECT_EQ("42 and abc1 and 1.2", result);
}

TEST(FormatTest, JoinArg) {
using fmt::join;
int v1[3] = { 1, 2, 3 };
Expand Down