Skip to content

Instantly share code, notes, and snippets.

@ppetr
Created November 20, 2021 16:19
Show Gist options
  • Save ppetr/de7a2b5e5541b071082df09b49bf6d34 to your computer and use it in GitHub Desktop.
Save ppetr/de7a2b5e5541b071082df09b49bf6d34 to your computer and use it in GitHub Desktop.
Converts a move-constructible type `U` that provides a value of type `T` via `T& operator*() const;` method into `std::shared_ptr<const T>`.
// Converts a move-constructible type `U` that provides a value of type `T` via
// `T& operator*() const;` method into `std::shared_ptr<const T>`.
template <typename U,
typename T = typename std::remove_reference<decltype(
*std::declval<typename std::add_const<U>::type>())>::type>
std::shared_ptr<T> ToSharedPtr(U container) {
static_assert(std::is_move_constructible<U>::value,
"The container type U must be move-constructible");
const U* on_heap = new U(std::move(container));
return std::shared_ptr<T>(&**on_heap, [on_heap](T*) { delete on_heap; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment