Skip to content
Open
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
3 changes: 2 additions & 1 deletion include/gsl/pointers
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,8 @@ template <class T>
not_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;


template <class T, class U = decltype(std::declval<const T&>().get()), bool = std::is_default_constructible<std::hash<U>>::value>
// T is conceptually a pointer so we don't have to worry about it being a reference and violating std::hash requirements
template <class T, class U = typename T::element_type, bool = std::is_default_constructible<std::hash<U>>::value>
Copy link
Member

Choose a reason for hiding this comment

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

Can you add a comment here saying that "T is conceptually a pointer so we don't have to worry about it being a reference and violating std::hash requirements".

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added the requested comment in commit 87b3085. The comment explains that T is conceptually a pointer so we don't have to worry about it being a reference and violating std::hash requirements.

struct not_null_hash
{
std::size_t operator()(const T& value) const { return std::hash<U>{}(value.get()); }
Expand Down
14 changes: 14 additions & 0 deletions tests/notnull_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -735,4 +735,18 @@ TEST(notnull_tests, TestStdHash)
EXPECT_FALSE(hash_nn(nn) == hash_intptr(&y));
EXPECT_FALSE(hash_nn(nn) == hash_intptr(nullptr));
}

{
auto x = std::make_shared<int>(42);
auto y = std::make_shared<int>(99);
not_null<std::shared_ptr<int>> nn{x};
const not_null<std::shared_ptr<int>> cnn{x};

std::hash<not_null<std::shared_ptr<int>>> hash_nn;
std::hash<std::shared_ptr<int>> hash_sharedptr;

EXPECT_TRUE(hash_nn(nn) == hash_sharedptr(x));
EXPECT_FALSE(hash_nn(nn) == hash_sharedptr(y));
EXPECT_TRUE(hash_nn(cnn) == hash_sharedptr(x));
}
}