Skip to content

Format to char* works for built-in types, but not user types #793

Closed
@wkenyon

Description

@wkenyon
#include <fmt/format.h>

enum class ExampleEnum : char
{
    A = '0',
    B = '1',
    C = '3',
    D = '?'
};


template <>
struct fmt::formatter<ExampleEnum> : fmt::formatter<fmt::string_view>
{
    using base = fmt::formatter<fmt::string_view>;

    template <typename FormatContext>
    auto format(const ExampleEnum& e, FormatContext& ctx)
        {
            switch (e)
            {
            case ExampleEnum::A:
                return base::format("A", ctx);
            case ExampleEnum::B:
                return base::format("B", ctx);
            case ExampleEnum::C:
                return base::format("C", ctx);
            case ExampleEnum::D:
                return base::format("D", ctx);
            };
            return base::format("NOT_RECOGNISED", ctx);
        }
};

int main() {
    char buf[80];
    memset(buf, 0, sizeof(buf));
    fmt::format_to(buf, "1: {}\n", "A");
    fmt::print(buf);

    char buf2[80];
    memset(buf2, 0, sizeof(buf2));
    fmt::format_to(buf2, "2: {}\n", ExampleEnum::A);
    fmt::print(buf2);

    fmt::print("3: {}\n", ExampleEnum::A);
    return 0;
}

As you can see, I'm trying to use format_to to write to a raw pointer. I know that you support 'iterators'. But a raw pointer is an iterator so this should work right? It seems to work for built-in types, but not this user defined formatter that inherits from string_view, as suggested in #787. I tested this on the latest master.

$ clang++ --std=c++14 -isystem external/fmt/include/  FmtBug.cpp -L bazel-bin/third_party/ -lfmt_lib
$ ./a.out
1: A
2: 
3: A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions