0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2024-07-01 00:08:22 +02:00

ircd: Add convenience templates for shared_from()/weak_from().

This commit is contained in:
Jason Volk 2016-11-08 11:43:09 -08:00
parent ae4057b1d5
commit c558df48bc
2 changed files with 38 additions and 1 deletions

View file

@ -42,6 +42,12 @@ is_shared_from_this()
return false;
}
// Convenience functions for types shared_from_this
template<class T> std::shared_ptr<const T> shared_from(const T &t);
template<class T> std::shared_ptr<T> shared_from(T &t);
template<class T> std::weak_ptr<const T> weak_from(const T &t);
template<class T> std::weak_ptr<T> weak_from(T &t);
/* Use the life_guard to keep an object alive within a function running in a context.
*
* Example:
@ -63,7 +69,7 @@ struct life_guard
template<class SFINAE = T>
life_guard(T &t,
typename std::enable_if<is_shared_from_this<SFINAE>(), void>::type * = 0)
:std::shared_ptr<T>(t.shared_from_this())
:std::shared_ptr<T>(shared_from(t))
{
}
@ -89,5 +95,33 @@ struct life_guard
}
};
template<class T>
std::weak_ptr<T>
weak_from(T &t)
{
return shared_from(t);
};
template<class T>
std::weak_ptr<const T>
weak_from(const T &t)
{
return shared_from(t);
};
template<class T>
std::shared_ptr<T>
shared_from(T &t)
{
return dynamic_pointer_cast<T>(t.shared_from_this());
};
template<class T>
std::shared_ptr<const T>
shared_from(const T &t)
{
return dynamic_pointer_cast<const T>(t.shared_from_this());
};
} // namespace ircd
#endif // __cplusplus

View file

@ -50,6 +50,9 @@ namespace ircd
using std::chrono::microseconds;
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
using std::static_pointer_cast;
using std::dynamic_pointer_cast;
using std::const_pointer_cast;
using ostream = std::ostream;
namespace ph = std::placeholders;
using namespace std::string_literals;