cast: Add is_generic_type<T>

This commit is contained in:
Eric Cousineau 2022-04-10 20:27:45 -04:00
parent c4e295287b
commit a3a7b39f5c
2 changed files with 17 additions and 1 deletions

View File

@ -36,6 +36,15 @@ class type_caster : public type_caster_base<type> {};
template <typename type>
using make_caster = type_caster<intrinsic_t<type>>;
template <typename T>
struct is_generic_type<T, enable_if_t<std::is_base_of<type_caster_generic, make_caster<T>>::value>>
: public std::true_type {};
template <typename T>
struct is_generic_type<T,
enable_if_t<!std::is_base_of<type_caster_generic, make_caster<T>>::value>>
: public std::false_type {};
// Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
template <typename T>
typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {

View File

@ -38,6 +38,11 @@ PYBIND11_NAMESPACE_BEGIN(detail)
class args_proxy;
bool isinstance_generic(handle obj, const std::type_info &tp);
// Indicates that type is generic and and does not have a specialized
// `type_caster<>` specialization. Defined in `cast.h`.
template <typename T, typename SFINAE = void>
struct is_generic_type;
// Accessor forward declarations
template <typename Policy>
class accessor;
@ -476,7 +481,7 @@ inline void raise_from(error_already_set &err, PyObject *type, const char *messa
/** \ingroup python_builtins
\rst
Return true if ``obj`` is an instance of ``T``. Type ``T`` must be a subclass of
`object` or a class which was exposed to Python as ``py::class_<T>``.
`object` or a class which was exposed to Python as ``py::class_<T>`` (generic).
\endrst */
template <typename T, detail::enable_if_t<std::is_base_of<object, T>::value, int> = 0>
bool isinstance(handle obj) {
@ -485,6 +490,8 @@ bool isinstance(handle obj) {
template <typename T, detail::enable_if_t<!std::is_base_of<object, T>::value, int> = 0>
bool isinstance(handle obj) {
static_assert(detail::is_generic_type<T>::value,
"isisntance<T>() requires specialization for this type");
return detail::isinstance_generic(obj, typeid(T));
}