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

fmt::ptr: Support function pointers #2131

Merged
merged 1 commit into from
Feb 9, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
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
7 changes: 7 additions & 0 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3739,6 +3739,13 @@ 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();
}
#if !FMT_MSC_VER
// MSVC lets function pointers decay to void pointers, so this
// overload is unnecessary.
template <typename T, typename... Args> inline const void* ptr(T (*fn)(Args...)) {
return detail::bit_cast<const void *>(fn);
}
#endif

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