Skip to content

Commit

Permalink
fmt::ptr: Support function pointers
Browse files Browse the repository at this point in the history
Passing a function pointer to fmt::ptr results in:

 In file included from /home/mac/git/fmt/test/gmock/gmock.h:238,
                  from /home/mac/git/fmt/test/format-test.cc:31:
 .../fmt/test/format-test.cc: In member function ‘virtual void FormatterTest_FormatPointer_Test::TestBody()’:
 .../fmt/test/format-test.cc:1486:56: error: no matching function for call to ‘ptr(void (&)(int, double, std::__cxx11::string))’
              format("{}", fmt::ptr(function_pointer_test)));

Let's add an overload to support that usage.
  • Loading branch information
mikecrowe committed Feb 9, 2021
1 parent 58aa045 commit 3e36bda
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
1 change: 1 addition & 0 deletions doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ Utilities
.. doxygenfunction:: fmt::ptr(const T *p)
.. doxygenfunction:: fmt::ptr(const std::unique_ptr<T> &p)
.. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p)
.. doxygenfunction:: fmt::ptr(T (*fn)(Args...))

.. doxygenfunction:: fmt::to_string(const T &value)

Expand Down
3 changes: 3 additions & 0 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3739,6 +3739,9 @@ template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) {
template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) {
return p.get();
}
template <typename T, typename... Args> inline const void* ptr(T (*fn)(Args...)) {
return detail::bit_cast<const void *>(fn);
}

class bytes {
private:
Expand Down
5 changes: 5 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,9 @@ TEST(FormatterTest, FormatUCharString) {
EXPECT_EQ("test", format("{0:s}", ptr));
}

void function_pointer_test(int, double, std::string) {
}

TEST(FormatterTest, FormatPointer) {
check_unknown_types(reinterpret_cast<void*>(0x1234), "p", "pointer");
EXPECT_EQ("0x0", format("{0}", static_cast<void*>(nullptr)));
Expand All @@ -1479,6 +1482,8 @@ TEST(FormatterTest, FormatPointer) {
EXPECT_EQ(format("{}", fmt::ptr(up.get())), format("{}", fmt::ptr(up)));
std::shared_ptr<int> sp(new int(1));
EXPECT_EQ(format("{}", fmt::ptr(sp.get())), format("{}", fmt::ptr(sp)));
EXPECT_EQ(format("{}", fmt::detail::bit_cast<const void *>(&function_pointer_test)),
format("{}", fmt::ptr(function_pointer_test)));
EXPECT_EQ("0x0", format("{}", nullptr));
}

Expand Down

0 comments on commit 3e36bda

Please sign in to comment.