Skip to content

Can't specialize formatter for templated ranged class #751

@drrlvn

Description

@drrlvn

If I include fmt/ranges.h I cannot specialize fmt::formatter for my type that is ranged and templated.
Say I have this class:

template<typename T>
class Foo {
public:
    ...
    const_iterator begin() const { ... }
    const_iterator cbegin() const { ... }
    ...
};

When trying to provide a specialization of fmt::formatter for this class:

template<typename T>
struct formatter<Foo<T>> {
    ...
};

I get an ambiguous template instantiation error because of the specialization in fmt/ranges.h:

include/fmt/core.h:529:56: error: ambiguous template instantiation for ‘struct fmt::v5::formatter<Foo<int>, char, void>’
     typename Context::template formatter_type<T>::type f;
                                                        ^
In file included from ...:
include/fmt/ranges.h:199:8: note: candidates are: ‘template<class RangeT, class Char> struct fmt::v5::formatter<RangeT, Char, typename std::enable_if<fmt::v5::internal::is_range<T>::value>::type> [with RangeT = Foo<int>; Char = char]’
 struct formatter< RangeT, Char,
        ^~~~~~~~~~~~~~~~~~~~~~~~
     typename std::enable_if<fmt::internal::is_range<RangeT>::value>::type> {
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from ...:
foo.cpp: note:                 ‘template<class T> struct fmt::v5::formatter<Foo<T> > [with T = int]’
     struct formatter<Foo<T>> {
            ^~~~~~~~~~~~~~~~~

As a workaround I can force fmt::internal::is_range to be false:

namespace fmt::internal {

template<typename T>
struct is_range<Foo<T>> : std::false_type {};

} // namespace fmt::internal

But obviously I would want to avoid defining anything in an internal namespace.

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