Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:06:14

0001 /*
0002     pybind11/cast.h: Partial template specializations to cast between
0003     C++ and Python types
0004 
0005     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0006 
0007     All rights reserved. Use of this source code is governed by a
0008     BSD-style license that can be found in the LICENSE file.
0009 */
0010 
0011 #pragma once
0012 
0013 #include "detail/common.h"
0014 #include "detail/descr.h"
0015 #include "detail/type_caster_base.h"
0016 #include "detail/typeid.h"
0017 #include "pytypes.h"
0018 
0019 #include <array>
0020 #include <cstring>
0021 #include <functional>
0022 #include <iosfwd>
0023 #include <iterator>
0024 #include <memory>
0025 #include <string>
0026 #include <tuple>
0027 #include <type_traits>
0028 #include <utility>
0029 #include <vector>
0030 
0031 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0032 
0033 PYBIND11_WARNING_DISABLE_MSVC(4127)
0034 
0035 PYBIND11_NAMESPACE_BEGIN(detail)
0036 
0037 template <typename type, typename SFINAE = void>
0038 class type_caster : public type_caster_base<type> {};
0039 template <typename type>
0040 using make_caster = type_caster<intrinsic_t<type>>;
0041 
0042 // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
0043 template <typename T>
0044 typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
0045     using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
0046     return caster.operator result_t();
0047 }
0048 template <typename T>
0049 typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
0050 cast_op(make_caster<T> &&caster) {
0051     using result_t = typename make_caster<T>::template cast_op_type<
0052         typename std::add_rvalue_reference<T>::type>; // See PR #4893
0053     return std::move(caster).operator result_t();
0054 }
0055 
0056 template <typename type>
0057 class type_caster<std::reference_wrapper<type>> {
0058 private:
0059     using caster_t = make_caster<type>;
0060     caster_t subcaster;
0061     using reference_t = type &;
0062     using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
0063 
0064     static_assert(
0065         std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
0066             || std::is_same<reference_t, subcaster_cast_op_type>::value,
0067         "std::reference_wrapper<T> caster requires T to have a caster with an "
0068         "`operator T &()` or `operator const T &()`");
0069 
0070 public:
0071     bool load(handle src, bool convert) { return subcaster.load(src, convert); }
0072     static constexpr auto name = caster_t::name;
0073     static handle
0074     cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
0075         // It is definitely wrong to take ownership of this pointer, so mask that rvp
0076         if (policy == return_value_policy::take_ownership
0077             || policy == return_value_policy::automatic) {
0078             policy = return_value_policy::automatic_reference;
0079         }
0080         return caster_t::cast(&src.get(), policy, parent);
0081     }
0082     template <typename T>
0083     using cast_op_type = std::reference_wrapper<type>;
0084     explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
0085 };
0086 
0087 #define PYBIND11_TYPE_CASTER(type, py_name)                                                       \
0088 protected:                                                                                        \
0089     type value;                                                                                   \
0090                                                                                                   \
0091 public:                                                                                           \
0092     static constexpr auto name = py_name;                                                         \
0093     template <typename T_,                                                                        \
0094               ::pybind11::detail::enable_if_t<                                                    \
0095                   std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value,                 \
0096                   int>                                                                            \
0097               = 0>                                                                                \
0098     static ::pybind11::handle cast(                                                               \
0099         T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) {             \
0100         if (!src)                                                                                 \
0101             return ::pybind11::none().release();                                                  \
0102         if (policy == ::pybind11::return_value_policy::take_ownership) {                          \
0103             auto h = cast(std::move(*src), policy, parent);                                       \
0104             delete src;                                                                           \
0105             return h;                                                                             \
0106         }                                                                                         \
0107         return cast(*src, policy, parent);                                                        \
0108     }                                                                                             \
0109     operator type *() { return &value; }               /* NOLINT(bugprone-macro-parentheses) */   \
0110     operator type &() { return value; }                /* NOLINT(bugprone-macro-parentheses) */   \
0111     operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */   \
0112     template <typename T_>                                                                        \
0113     using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
0114 
0115 template <typename CharT>
0116 using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
0117 #if defined(PYBIND11_HAS_U8STRING)
0118                                 std::is_same<CharT, char8_t>, /* std::u8string */
0119 #endif
0120                                 std::is_same<CharT, char16_t>, /* std::u16string */
0121                                 std::is_same<CharT, char32_t>, /* std::u32string */
0122                                 std::is_same<CharT, wchar_t>   /* std::wstring */
0123                                 >;
0124 
0125 template <typename T>
0126 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
0127     using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
0128     using _py_type_1 = conditional_t<std::is_signed<T>::value,
0129                                      _py_type_0,
0130                                      typename std::make_unsigned<_py_type_0>::type>;
0131     using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
0132 
0133 public:
0134     bool load(handle src, bool convert) {
0135         py_type py_value;
0136 
0137         if (!src) {
0138             return false;
0139         }
0140 
0141 #if !defined(PYPY_VERSION)
0142         auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
0143 #else
0144         // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
0145         // while CPython only considers the existence of `nb_index`/`__index__`.
0146         auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
0147 #endif
0148 
0149         if (std::is_floating_point<T>::value) {
0150             if (convert || PyFloat_Check(src.ptr())) {
0151                 py_value = (py_type) PyFloat_AsDouble(src.ptr());
0152             } else {
0153                 return false;
0154             }
0155         } else if (PyFloat_Check(src.ptr())
0156                    || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
0157             return false;
0158         } else {
0159             handle src_or_index = src;
0160             // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
0161 #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
0162             object index;
0163             if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
0164                 index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
0165                 if (!index) {
0166                     PyErr_Clear();
0167                     if (!convert)
0168                         return false;
0169                 } else {
0170                     src_or_index = index;
0171                 }
0172             }
0173 #endif
0174             if (std::is_unsigned<py_type>::value) {
0175                 py_value = as_unsigned<py_type>(src_or_index.ptr());
0176             } else { // signed integer:
0177                 py_value = sizeof(T) <= sizeof(long)
0178                                ? (py_type) PyLong_AsLong(src_or_index.ptr())
0179                                : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
0180             }
0181         }
0182 
0183         // Python API reported an error
0184         bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
0185 
0186         // Check to see if the conversion is valid (integers should match exactly)
0187         // Signed/unsigned checks happen elsewhere
0188         if (py_err
0189             || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
0190                 && py_value != (py_type) (T) py_value)) {
0191             PyErr_Clear();
0192             if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
0193                 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
0194                                                          ? PyNumber_Float(src.ptr())
0195                                                          : PyNumber_Long(src.ptr()));
0196                 PyErr_Clear();
0197                 return load(tmp, false);
0198             }
0199             return false;
0200         }
0201 
0202         value = (T) py_value;
0203         return true;
0204     }
0205 
0206     template <typename U = T>
0207     static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
0208     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0209         return PyFloat_FromDouble((double) src);
0210     }
0211 
0212     template <typename U = T>
0213     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0214                                        && (sizeof(U) <= sizeof(long)),
0215                                    handle>::type
0216     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0217         return PYBIND11_LONG_FROM_SIGNED((long) src);
0218     }
0219 
0220     template <typename U = T>
0221     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0222                                        && (sizeof(U) <= sizeof(unsigned long)),
0223                                    handle>::type
0224     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0225         return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
0226     }
0227 
0228     template <typename U = T>
0229     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
0230                                        && (sizeof(U) > sizeof(long)),
0231                                    handle>::type
0232     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0233         return PyLong_FromLongLong((long long) src);
0234     }
0235 
0236     template <typename U = T>
0237     static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
0238                                        && (sizeof(U) > sizeof(unsigned long)),
0239                                    handle>::type
0240     cast(U src, return_value_policy /* policy */, handle /* parent */) {
0241         return PyLong_FromUnsignedLongLong((unsigned long long) src);
0242     }
0243 
0244     PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
0245 };
0246 
0247 template <typename T>
0248 struct void_caster {
0249 public:
0250     bool load(handle src, bool) {
0251         if (src && src.is_none()) {
0252             return true;
0253         }
0254         return false;
0255     }
0256     static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
0257         return none().release();
0258     }
0259     PYBIND11_TYPE_CASTER(T, const_name("None"));
0260 };
0261 
0262 template <>
0263 class type_caster<void_type> : public void_caster<void_type> {};
0264 
0265 template <>
0266 class type_caster<void> : public type_caster<void_type> {
0267 public:
0268     using type_caster<void_type>::cast;
0269 
0270     bool load(handle h, bool) {
0271         if (!h) {
0272             return false;
0273         }
0274         if (h.is_none()) {
0275             value = nullptr;
0276             return true;
0277         }
0278 
0279         /* Check if this is a capsule */
0280         if (isinstance<capsule>(h)) {
0281             value = reinterpret_borrow<capsule>(h);
0282             return true;
0283         }
0284 
0285         /* Check if this is a C++ type */
0286         const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
0287         if (bases.size() == 1) { // Only allowing loading from a single-value type
0288             value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
0289             return true;
0290         }
0291 
0292         /* Fail */
0293         return false;
0294     }
0295 
0296     static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
0297         if (ptr) {
0298             return capsule(ptr).release();
0299         }
0300         return none().release();
0301     }
0302 
0303     template <typename T>
0304     using cast_op_type = void *&;
0305     explicit operator void *&() { return value; }
0306     static constexpr auto name = const_name("capsule");
0307 
0308 private:
0309     void *value = nullptr;
0310 };
0311 
0312 template <>
0313 class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
0314 
0315 template <>
0316 class type_caster<bool> {
0317 public:
0318     bool load(handle src, bool convert) {
0319         if (!src) {
0320             return false;
0321         }
0322         if (src.ptr() == Py_True) {
0323             value = true;
0324             return true;
0325         }
0326         if (src.ptr() == Py_False) {
0327             value = false;
0328             return true;
0329         }
0330         if (convert || is_numpy_bool(src)) {
0331             // (allow non-implicit conversion for numpy booleans), use strncmp
0332             // since NumPy 1.x had an additional trailing underscore.
0333 
0334             Py_ssize_t res = -1;
0335             if (src.is_none()) {
0336                 res = 0; // None is implicitly converted to False
0337             }
0338 #if defined(PYPY_VERSION)
0339             // On PyPy, check that "__bool__" attr exists
0340             else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
0341                 res = PyObject_IsTrue(src.ptr());
0342             }
0343 #else
0344             // Alternate approach for CPython: this does the same as the above, but optimized
0345             // using the CPython API so as to avoid an unneeded attribute lookup.
0346             else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
0347                 if (PYBIND11_NB_BOOL(tp_as_number)) {
0348                     res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
0349                 }
0350             }
0351 #endif
0352             if (res == 0 || res == 1) {
0353                 value = (res != 0);
0354                 return true;
0355             }
0356             PyErr_Clear();
0357         }
0358         return false;
0359     }
0360     static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
0361         return handle(src ? Py_True : Py_False).inc_ref();
0362     }
0363     PYBIND11_TYPE_CASTER(bool, const_name("bool"));
0364 
0365 private:
0366     // Test if an object is a NumPy boolean (without fetching the type).
0367     static inline bool is_numpy_bool(handle object) {
0368         const char *type_name = Py_TYPE(object.ptr())->tp_name;
0369         // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
0370         return std::strcmp("numpy.bool", type_name) == 0
0371                || std::strcmp("numpy.bool_", type_name) == 0;
0372     }
0373 };
0374 
0375 // Helper class for UTF-{8,16,32} C++ stl strings:
0376 template <typename StringType, bool IsView = false>
0377 struct string_caster {
0378     using CharT = typename StringType::value_type;
0379 
0380     // Simplify life by being able to assume standard char sizes (the standard only guarantees
0381     // minimums, but Python requires exact sizes)
0382     static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
0383                   "Unsupported char size != 1");
0384 #if defined(PYBIND11_HAS_U8STRING)
0385     static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
0386                   "Unsupported char8_t size != 1");
0387 #endif
0388     static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
0389                   "Unsupported char16_t size != 2");
0390     static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
0391                   "Unsupported char32_t size != 4");
0392     // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
0393     static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
0394                   "Unsupported wchar_t size != 2/4");
0395     static constexpr size_t UTF_N = 8 * sizeof(CharT);
0396 
0397     bool load(handle src, bool) {
0398         handle load_src = src;
0399         if (!src) {
0400             return false;
0401         }
0402         if (!PyUnicode_Check(load_src.ptr())) {
0403             return load_raw(load_src);
0404         }
0405 
0406         // For UTF-8 we avoid the need for a temporary `bytes` object by using
0407         // `PyUnicode_AsUTF8AndSize`.
0408         if (UTF_N == 8) {
0409             Py_ssize_t size = -1;
0410             const auto *buffer
0411                 = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
0412             if (!buffer) {
0413                 PyErr_Clear();
0414                 return false;
0415             }
0416             value = StringType(buffer, static_cast<size_t>(size));
0417             return true;
0418         }
0419 
0420         auto utfNbytes
0421             = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
0422                                                                   UTF_N == 8    ? "utf-8"
0423                                                                   : UTF_N == 16 ? "utf-16"
0424                                                                                 : "utf-32",
0425                                                                   nullptr));
0426         if (!utfNbytes) {
0427             PyErr_Clear();
0428             return false;
0429         }
0430 
0431         const auto *buffer
0432             = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
0433         size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
0434         // Skip BOM for UTF-16/32
0435         if (UTF_N > 8) {
0436             buffer++;
0437             length--;
0438         }
0439         value = StringType(buffer, length);
0440 
0441         // If we're loading a string_view we need to keep the encoded Python object alive:
0442         if (IsView) {
0443             loader_life_support::add_patient(utfNbytes);
0444         }
0445 
0446         return true;
0447     }
0448 
0449     static handle
0450     cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
0451         const char *buffer = reinterpret_cast<const char *>(src.data());
0452         auto nbytes = ssize_t(src.size() * sizeof(CharT));
0453         handle s = decode_utfN(buffer, nbytes);
0454         if (!s) {
0455             throw error_already_set();
0456         }
0457         return s;
0458     }
0459 
0460     PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
0461 
0462 private:
0463     static handle decode_utfN(const char *buffer, ssize_t nbytes) {
0464 #if !defined(PYPY_VERSION)
0465         return UTF_N == 8    ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
0466                : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
0467                              : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
0468 #else
0469         // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
0470         // well), so bypass the whole thing by just passing the encoding as a string value, which
0471         // works properly:
0472         return PyUnicode_Decode(buffer,
0473                                 nbytes,
0474                                 UTF_N == 8    ? "utf-8"
0475                                 : UTF_N == 16 ? "utf-16"
0476                                               : "utf-32",
0477                                 nullptr);
0478 #endif
0479     }
0480 
0481     // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
0482     // without any encoding/decoding attempt).  For other C++ char sizes this is a no-op.
0483     // which supports loading a unicode from a str, doesn't take this path.
0484     template <typename C = CharT>
0485     bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
0486         if (PYBIND11_BYTES_CHECK(src.ptr())) {
0487             // We were passed raw bytes; accept it into a std::string or char*
0488             // without any encoding attempt.
0489             const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
0490             if (!bytes) {
0491                 pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
0492             }
0493             value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
0494             return true;
0495         }
0496         if (PyByteArray_Check(src.ptr())) {
0497             // We were passed a bytearray; accept it into a std::string or char*
0498             // without any encoding attempt.
0499             const char *bytearray = PyByteArray_AsString(src.ptr());
0500             if (!bytearray) {
0501                 pybind11_fail("Unexpected PyByteArray_AsString() failure.");
0502             }
0503             value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
0504             return true;
0505         }
0506 
0507         return false;
0508     }
0509 
0510     template <typename C = CharT>
0511     bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
0512         return false;
0513     }
0514 };
0515 
0516 template <typename CharT, class Traits, class Allocator>
0517 struct type_caster<std::basic_string<CharT, Traits, Allocator>,
0518                    enable_if_t<is_std_char_type<CharT>::value>>
0519     : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
0520 
0521 #ifdef PYBIND11_HAS_STRING_VIEW
0522 template <typename CharT, class Traits>
0523 struct type_caster<std::basic_string_view<CharT, Traits>,
0524                    enable_if_t<is_std_char_type<CharT>::value>>
0525     : string_caster<std::basic_string_view<CharT, Traits>, true> {};
0526 #endif
0527 
0528 // Type caster for C-style strings.  We basically use a std::string type caster, but also add the
0529 // ability to use None as a nullptr char* (which the string caster doesn't allow).
0530 template <typename CharT>
0531 struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
0532     using StringType = std::basic_string<CharT>;
0533     using StringCaster = make_caster<StringType>;
0534     StringCaster str_caster;
0535     bool none = false;
0536     CharT one_char = 0;
0537 
0538 public:
0539     bool load(handle src, bool convert) {
0540         if (!src) {
0541             return false;
0542         }
0543         if (src.is_none()) {
0544             // Defer accepting None to other overloads (if we aren't in convert mode):
0545             if (!convert) {
0546                 return false;
0547             }
0548             none = true;
0549             return true;
0550         }
0551         return str_caster.load(src, convert);
0552     }
0553 
0554     static handle cast(const CharT *src, return_value_policy policy, handle parent) {
0555         if (src == nullptr) {
0556             return pybind11::none().release();
0557         }
0558         return StringCaster::cast(StringType(src), policy, parent);
0559     }
0560 
0561     static handle cast(CharT src, return_value_policy policy, handle parent) {
0562         if (std::is_same<char, CharT>::value) {
0563             handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
0564             if (!s) {
0565                 throw error_already_set();
0566             }
0567             return s;
0568         }
0569         return StringCaster::cast(StringType(1, src), policy, parent);
0570     }
0571 
0572     explicit operator CharT *() {
0573         return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
0574     }
0575     explicit operator CharT &() {
0576         if (none) {
0577             throw value_error("Cannot convert None to a character");
0578         }
0579 
0580         auto &value = static_cast<StringType &>(str_caster);
0581         size_t str_len = value.size();
0582         if (str_len == 0) {
0583             throw value_error("Cannot convert empty string to a character");
0584         }
0585 
0586         // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
0587         // is too high, and one for multiple unicode characters (caught later), so we need to
0588         // figure out how long the first encoded character is in bytes to distinguish between these
0589         // two errors.  We also allow want to allow unicode characters U+0080 through U+00FF, as
0590         // those can fit into a single char value.
0591         if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
0592             auto v0 = static_cast<unsigned char>(value[0]);
0593             // low bits only: 0-127
0594             // 0b110xxxxx - start of 2-byte sequence
0595             // 0b1110xxxx - start of 3-byte sequence
0596             // 0b11110xxx - start of 4-byte sequence
0597             size_t char0_bytes = (v0 & 0x80) == 0      ? 1
0598                                  : (v0 & 0xE0) == 0xC0 ? 2
0599                                  : (v0 & 0xF0) == 0xE0 ? 3
0600                                                        : 4;
0601 
0602             if (char0_bytes == str_len) {
0603                 // If we have a 128-255 value, we can decode it into a single char:
0604                 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
0605                     one_char = static_cast<CharT>(((v0 & 3) << 6)
0606                                                   + (static_cast<unsigned char>(value[1]) & 0x3F));
0607                     return one_char;
0608                 }
0609                 // Otherwise we have a single character, but it's > U+00FF
0610                 throw value_error("Character code point not in range(0x100)");
0611             }
0612         }
0613 
0614         // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
0615         // surrogate pair with total length 2 instantly indicates a range error (but not a "your
0616         // string was too long" error).
0617         else if (StringCaster::UTF_N == 16 && str_len == 2) {
0618             one_char = static_cast<CharT>(value[0]);
0619             if (one_char >= 0xD800 && one_char < 0xE000) {
0620                 throw value_error("Character code point not in range(0x10000)");
0621             }
0622         }
0623 
0624         if (str_len != 1) {
0625             throw value_error("Expected a character, but multi-character string found");
0626         }
0627 
0628         one_char = value[0];
0629         return one_char;
0630     }
0631 
0632     static constexpr auto name = const_name(PYBIND11_STRING_NAME);
0633     template <typename _T>
0634     using cast_op_type = pybind11::detail::cast_op_type<_T>;
0635 };
0636 
0637 // Base implementation for std::tuple and std::pair
0638 template <template <typename...> class Tuple, typename... Ts>
0639 class tuple_caster {
0640     using type = Tuple<Ts...>;
0641     static constexpr auto size = sizeof...(Ts);
0642     using indices = make_index_sequence<size>;
0643 
0644 public:
0645     bool load(handle src, bool convert) {
0646         if (!isinstance<sequence>(src)) {
0647             return false;
0648         }
0649         const auto seq = reinterpret_borrow<sequence>(src);
0650         if (seq.size() != size) {
0651             return false;
0652         }
0653         return load_impl(seq, convert, indices{});
0654     }
0655 
0656     template <typename T>
0657     static handle cast(T &&src, return_value_policy policy, handle parent) {
0658         return cast_impl(std::forward<T>(src), policy, parent, indices{});
0659     }
0660 
0661     // copied from the PYBIND11_TYPE_CASTER macro
0662     template <typename T>
0663     static handle cast(T *src, return_value_policy policy, handle parent) {
0664         if (!src) {
0665             return none().release();
0666         }
0667         if (policy == return_value_policy::take_ownership) {
0668             auto h = cast(std::move(*src), policy, parent);
0669             delete src;
0670             return h;
0671         }
0672         return cast(*src, policy, parent);
0673     }
0674 
0675     static constexpr auto name = const_name("tuple[")
0676                                  + ::pybind11::detail::concat(make_caster<Ts>::name...)
0677                                  + const_name("]");
0678 
0679     template <typename T>
0680     using cast_op_type = type;
0681 
0682     explicit operator type() & { return implicit_cast(indices{}); }
0683     explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
0684 
0685 protected:
0686     template <size_t... Is>
0687     type implicit_cast(index_sequence<Is...>) & {
0688         return type(cast_op<Ts>(std::get<Is>(subcasters))...);
0689     }
0690     template <size_t... Is>
0691     type implicit_cast(index_sequence<Is...>) && {
0692         return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
0693     }
0694 
0695     static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
0696 
0697     template <size_t... Is>
0698     bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
0699 #ifdef __cpp_fold_expressions
0700         if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
0701             return false;
0702         }
0703 #else
0704         for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
0705             if (!r) {
0706                 return false;
0707             }
0708         }
0709 #endif
0710         return true;
0711     }
0712 
0713     /* Implementation: Convert a C++ tuple into a Python tuple */
0714     template <typename T, size_t... Is>
0715     static handle
0716     cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
0717         PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
0718         PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
0719         std::array<object, size> entries{{reinterpret_steal<object>(
0720             make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
0721         for (const auto &entry : entries) {
0722             if (!entry) {
0723                 return handle();
0724             }
0725         }
0726         tuple result(size);
0727         int counter = 0;
0728         for (auto &entry : entries) {
0729             PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
0730         }
0731         return result.release();
0732     }
0733 
0734     Tuple<make_caster<Ts>...> subcasters;
0735 };
0736 
0737 template <typename T1, typename T2>
0738 class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
0739 
0740 template <typename... Ts>
0741 class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
0742 
0743 template <>
0744 class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
0745 public:
0746     // PEP 484 specifies this syntax for an empty tuple
0747     static constexpr auto name = const_name("tuple[()]");
0748 };
0749 
0750 /// Helper class which abstracts away certain actions. Users can provide specializations for
0751 /// custom holders, but it's only necessary if the type has a non-standard interface.
0752 template <typename T>
0753 struct holder_helper {
0754     static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
0755 };
0756 
0757 /// Type caster for holder types like std::shared_ptr, etc.
0758 /// The SFINAE hook is provided to help work around the current lack of support
0759 /// for smart-pointer interoperability. Please consider it an implementation
0760 /// detail that may change in the future, as formal support for smart-pointer
0761 /// interoperability is added into pybind11.
0762 template <typename type, typename holder_type, typename SFINAE = void>
0763 struct copyable_holder_caster : public type_caster_base<type> {
0764 public:
0765     using base = type_caster_base<type>;
0766     static_assert(std::is_base_of<base, type_caster<type>>::value,
0767                   "Holder classes are only supported for custom types");
0768     using base::base;
0769     using base::cast;
0770     using base::typeinfo;
0771     using base::value;
0772 
0773     bool load(handle src, bool convert) {
0774         return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
0775     }
0776 
0777     explicit operator type *() { return this->value; }
0778     // static_cast works around compiler error with MSVC 17 and CUDA 10.2
0779     // see issue #2180
0780     explicit operator type &() { return *(static_cast<type *>(this->value)); }
0781     explicit operator holder_type *() { return std::addressof(holder); }
0782     explicit operator holder_type &() { return holder; }
0783 
0784     static handle cast(const holder_type &src, return_value_policy, handle) {
0785         const auto *ptr = holder_helper<holder_type>::get(src);
0786         return type_caster_base<type>::cast_holder(ptr, &src);
0787     }
0788 
0789 protected:
0790     friend class type_caster_generic;
0791     void check_holder_compat() {
0792         if (typeinfo->default_holder) {
0793             throw cast_error("Unable to load a custom holder type from a default-holder instance");
0794         }
0795     }
0796 
0797     void load_value(value_and_holder &&v_h) {
0798         if (v_h.holder_constructed()) {
0799             value = v_h.value_ptr();
0800             holder = v_h.template holder<holder_type>();
0801             return;
0802         }
0803         throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
0804 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0805                          "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
0806                          "type information)");
0807 #else
0808                          "of type '"
0809                          + type_id<holder_type>() + "''");
0810 #endif
0811     }
0812 
0813     template <typename T = holder_type,
0814               detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
0815     bool try_implicit_casts(handle, bool) {
0816         return false;
0817     }
0818 
0819     template <typename T = holder_type,
0820               detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
0821     bool try_implicit_casts(handle src, bool convert) {
0822         for (auto &cast : typeinfo->implicit_casts) {
0823             copyable_holder_caster sub_caster(*cast.first);
0824             if (sub_caster.load(src, convert)) {
0825                 value = cast.second(sub_caster.value);
0826                 holder = holder_type(sub_caster.holder, (type *) value);
0827                 return true;
0828             }
0829         }
0830         return false;
0831     }
0832 
0833     static bool try_direct_conversions(handle) { return false; }
0834 
0835     holder_type holder;
0836 };
0837 
0838 /// Specialize for the common std::shared_ptr, so users don't need to
0839 template <typename T>
0840 class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
0841 
0842 /// Type caster for holder types like std::unique_ptr.
0843 /// Please consider the SFINAE hook an implementation detail, as explained
0844 /// in the comment for the copyable_holder_caster.
0845 template <typename type, typename holder_type, typename SFINAE = void>
0846 struct move_only_holder_caster {
0847     static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
0848                   "Holder classes are only supported for custom types");
0849 
0850     static handle cast(holder_type &&src, return_value_policy, handle) {
0851         auto *ptr = holder_helper<holder_type>::get(src);
0852         return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
0853     }
0854     static constexpr auto name = type_caster_base<type>::name;
0855 };
0856 
0857 template <typename type, typename deleter>
0858 class type_caster<std::unique_ptr<type, deleter>>
0859     : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
0860 
0861 template <typename type, typename holder_type>
0862 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
0863                                          copyable_holder_caster<type, holder_type>,
0864                                          move_only_holder_caster<type, holder_type>>;
0865 
0866 template <typename T, bool Value = false>
0867 struct always_construct_holder {
0868     static constexpr bool value = Value;
0869 };
0870 
0871 /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
0872 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...)                                      \
0873     PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \
0874     namespace detail {                                                                            \
0875     template <typename type>                                                                      \
0876     struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> {  \
0877     };                                                                                            \
0878     template <typename type>                                                                      \
0879     class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>>               \
0880         : public type_caster_holder<type, holder_type> {};                                        \
0881     }                                                                                             \
0882     PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
0883 
0884 // PYBIND11_DECLARE_HOLDER_TYPE holder types:
0885 template <typename base, typename holder>
0886 struct is_holder_type
0887     : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
0888 // Specialization for always-supported unique_ptr holders:
0889 template <typename base, typename deleter>
0890 struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
0891 
0892 #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
0893 
0894 // This leads to compilation errors if a specialization is missing.
0895 template <typename T>
0896 struct handle_type_name;
0897 
0898 #else
0899 
0900 template <typename T>
0901 struct handle_type_name {
0902     static constexpr auto name = const_name<T>();
0903 };
0904 
0905 #endif
0906 
0907 template <>
0908 struct handle_type_name<object> {
0909     static constexpr auto name = const_name("object");
0910 };
0911 template <>
0912 struct handle_type_name<list> {
0913     static constexpr auto name = const_name("list");
0914 };
0915 template <>
0916 struct handle_type_name<dict> {
0917     static constexpr auto name = const_name("dict");
0918 };
0919 template <>
0920 struct handle_type_name<anyset> {
0921     static constexpr auto name = const_name("Union[set, frozenset]");
0922 };
0923 template <>
0924 struct handle_type_name<set> {
0925     static constexpr auto name = const_name("set");
0926 };
0927 template <>
0928 struct handle_type_name<frozenset> {
0929     static constexpr auto name = const_name("frozenset");
0930 };
0931 template <>
0932 struct handle_type_name<str> {
0933     static constexpr auto name = const_name("str");
0934 };
0935 template <>
0936 struct handle_type_name<tuple> {
0937     static constexpr auto name = const_name("tuple");
0938 };
0939 template <>
0940 struct handle_type_name<bool_> {
0941     static constexpr auto name = const_name("bool");
0942 };
0943 template <>
0944 struct handle_type_name<bytes> {
0945     static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
0946 };
0947 template <>
0948 struct handle_type_name<buffer> {
0949     static constexpr auto name = const_name("Buffer");
0950 };
0951 template <>
0952 struct handle_type_name<int_> {
0953     static constexpr auto name = const_name("int");
0954 };
0955 template <>
0956 struct handle_type_name<iterable> {
0957     static constexpr auto name = const_name("Iterable");
0958 };
0959 template <>
0960 struct handle_type_name<iterator> {
0961     static constexpr auto name = const_name("Iterator");
0962 };
0963 template <>
0964 struct handle_type_name<float_> {
0965     static constexpr auto name = const_name("float");
0966 };
0967 template <>
0968 struct handle_type_name<function> {
0969     static constexpr auto name = const_name("Callable");
0970 };
0971 template <>
0972 struct handle_type_name<handle> {
0973     static constexpr auto name = handle_type_name<object>::name;
0974 };
0975 template <>
0976 struct handle_type_name<none> {
0977     static constexpr auto name = const_name("None");
0978 };
0979 template <>
0980 struct handle_type_name<sequence> {
0981     static constexpr auto name = const_name("Sequence");
0982 };
0983 template <>
0984 struct handle_type_name<bytearray> {
0985     static constexpr auto name = const_name("bytearray");
0986 };
0987 template <>
0988 struct handle_type_name<memoryview> {
0989     static constexpr auto name = const_name("memoryview");
0990 };
0991 template <>
0992 struct handle_type_name<slice> {
0993     static constexpr auto name = const_name("slice");
0994 };
0995 template <>
0996 struct handle_type_name<type> {
0997     static constexpr auto name = const_name("type");
0998 };
0999 template <>
1000 struct handle_type_name<capsule> {
1001     static constexpr auto name = const_name("capsule");
1002 };
1003 template <>
1004 struct handle_type_name<ellipsis> {
1005     static constexpr auto name = const_name("ellipsis");
1006 };
1007 template <>
1008 struct handle_type_name<weakref> {
1009     static constexpr auto name = const_name("weakref");
1010 };
1011 template <>
1012 struct handle_type_name<args> {
1013     static constexpr auto name = const_name("*args");
1014 };
1015 template <>
1016 struct handle_type_name<kwargs> {
1017     static constexpr auto name = const_name("**kwargs");
1018 };
1019 template <>
1020 struct handle_type_name<obj_attr_accessor> {
1021     static constexpr auto name = const_name<obj_attr_accessor>();
1022 };
1023 template <>
1024 struct handle_type_name<str_attr_accessor> {
1025     static constexpr auto name = const_name<str_attr_accessor>();
1026 };
1027 template <>
1028 struct handle_type_name<item_accessor> {
1029     static constexpr auto name = const_name<item_accessor>();
1030 };
1031 template <>
1032 struct handle_type_name<sequence_accessor> {
1033     static constexpr auto name = const_name<sequence_accessor>();
1034 };
1035 template <>
1036 struct handle_type_name<list_accessor> {
1037     static constexpr auto name = const_name<list_accessor>();
1038 };
1039 template <>
1040 struct handle_type_name<tuple_accessor> {
1041     static constexpr auto name = const_name<tuple_accessor>();
1042 };
1043 
1044 template <typename type>
1045 struct pyobject_caster {
1046     template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1047     pyobject_caster() : value() {}
1048 
1049     // `type` may not be default constructible (e.g. frozenset, anyset).  Initializing `value`
1050     // to a nil handle is safe since it will only be accessed if `load` succeeds.
1051     template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1052     pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
1053 
1054     template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1055     bool load(handle src, bool /* convert */) {
1056         value = src;
1057         return static_cast<bool>(value);
1058     }
1059 
1060     template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1061     bool load(handle src, bool /* convert */) {
1062         if (!isinstance<type>(src)) {
1063             return false;
1064         }
1065         value = reinterpret_borrow<type>(src);
1066         return true;
1067     }
1068 
1069     static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1070         return src.inc_ref();
1071     }
1072     PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1073 };
1074 
1075 template <typename T>
1076 class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
1077 
1078 // Our conditions for enabling moving are quite restrictive:
1079 // At compile time:
1080 // - T needs to be a non-const, non-pointer, non-reference type
1081 // - type_caster<T>::operator T&() must exist
1082 // - the type must be move constructible (obviously)
1083 // At run-time:
1084 // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1085 //   must have ref_count() == 1)h
1086 // If any of the above are not satisfied, we fall back to copying.
1087 template <typename T>
1088 using move_is_plain_type
1089     = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
1090 template <typename T, typename SFINAE = void>
1091 struct move_always : std::false_type {};
1092 template <typename T>
1093 struct move_always<
1094     T,
1095     enable_if_t<
1096         all_of<move_is_plain_type<T>,
1097                negation<is_copy_constructible<T>>,
1098                is_move_constructible<T>,
1099                std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1100     : std::true_type {};
1101 template <typename T, typename SFINAE = void>
1102 struct move_if_unreferenced : std::false_type {};
1103 template <typename T>
1104 struct move_if_unreferenced<
1105     T,
1106     enable_if_t<
1107         all_of<move_is_plain_type<T>,
1108                negation<move_always<T>>,
1109                is_move_constructible<T>,
1110                std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1111     : std::true_type {};
1112 template <typename T>
1113 using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1114 
1115 // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1116 // reference or pointer to a local variable of the type_caster.  Basically, only
1117 // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1118 // everything else returns a reference/pointer to a local variable.
1119 template <typename type>
1120 using cast_is_temporary_value_reference
1121     = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1122                     && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1123                     && !std::is_same<intrinsic_t<type>, void>::value>;
1124 
1125 // When a value returned from a C++ function is being cast back to Python, we almost always want to
1126 // force `policy = move`, regardless of the return value policy the function/method was declared
1127 // with.
1128 template <typename Return, typename SFINAE = void>
1129 struct return_value_policy_override {
1130     static return_value_policy policy(return_value_policy p) { return p; }
1131 };
1132 
1133 template <typename Return>
1134 struct return_value_policy_override<
1135     Return,
1136     detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1137     static return_value_policy policy(return_value_policy p) {
1138         return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1139                    ? return_value_policy::move
1140                    : p;
1141     }
1142 };
1143 
1144 // Basic python -> C++ casting; throws if casting fails
1145 template <typename T, typename SFINAE>
1146 type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1147     static_assert(!detail::is_pyobject<T>::value,
1148                   "Internal error: type_caster should only be used for C++ types");
1149     if (!conv.load(handle, true)) {
1150 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1151         throw cast_error(
1152             "Unable to cast Python instance of type "
1153             + str(type::handle_of(handle)).cast<std::string>()
1154             + " to C++ type '?' (#define "
1155               "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1156 #else
1157         throw cast_error("Unable to cast Python instance of type "
1158                          + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1159                          + type_id<T>() + "'");
1160 #endif
1161     }
1162     return conv;
1163 }
1164 // Wrapper around the above that also constructs and returns a type_caster
1165 template <typename T>
1166 make_caster<T> load_type(const handle &handle) {
1167     make_caster<T> conv;
1168     load_type(conv, handle);
1169     return conv;
1170 }
1171 
1172 PYBIND11_NAMESPACE_END(detail)
1173 
1174 // pytype -> C++ type
1175 template <typename T,
1176           detail::enable_if_t<!detail::is_pyobject<T>::value
1177                                   && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1178                               int>
1179           = 0>
1180 T cast(const handle &handle) {
1181     using namespace detail;
1182     static_assert(!cast_is_temporary_value_reference<T>::value,
1183                   "Unable to cast type to reference: value is local to type caster");
1184     return cast_op<T>(load_type<T>(handle));
1185 }
1186 
1187 // pytype -> pytype (calls converting constructor)
1188 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1189 T cast(const handle &handle) {
1190     return T(reinterpret_borrow<object>(handle));
1191 }
1192 
1193 // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1194 // This is necessary for the case that `obj` is a temporary, and could
1195 // not possibly be different, given
1196 // 1. the established convention that the passed `handle` is borrowed, and
1197 // 2. we don't want to force all generic code using `cast<T>()` to special-case
1198 //    handling of `T` = `PyObject *` (to increment the reference count there).
1199 // It is the responsibility of the caller to ensure that the reference count
1200 // is decremented.
1201 template <typename T,
1202           typename Handle,
1203           detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1204                                   && detail::is_same_ignoring_cvref<Handle, handle>::value,
1205                               int>
1206           = 0>
1207 T cast(Handle &&handle) {
1208     return handle.inc_ref().ptr();
1209 }
1210 // To optimize way an inc_ref/dec_ref cycle:
1211 template <typename T,
1212           typename Object,
1213           detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1214                                   && detail::is_same_ignoring_cvref<Object, object>::value,
1215                               int>
1216           = 0>
1217 T cast(Object &&obj) {
1218     return obj.release().ptr();
1219 }
1220 
1221 // C++ type -> py::object
1222 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1223 object cast(T &&value,
1224             return_value_policy policy = return_value_policy::automatic_reference,
1225             handle parent = handle()) {
1226     using no_ref_T = typename std::remove_reference<T>::type;
1227     if (policy == return_value_policy::automatic) {
1228         policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::take_ownership
1229                  : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1230                                                       : return_value_policy::move;
1231     } else if (policy == return_value_policy::automatic_reference) {
1232         policy = std::is_pointer<no_ref_T>::value     ? return_value_policy::reference
1233                  : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1234                                                       : return_value_policy::move;
1235     }
1236     return reinterpret_steal<object>(
1237         detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1238 }
1239 
1240 template <typename T>
1241 T handle::cast() const {
1242     return pybind11::cast<T>(*this);
1243 }
1244 template <>
1245 inline void handle::cast() const {
1246     return;
1247 }
1248 
1249 template <typename T>
1250 detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1251     if (obj.ref_count() > 1) {
1252 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1253         throw cast_error(
1254             "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1255             + " instance to C++ rvalue: instance has multiple references"
1256               " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1257 #else
1258         throw cast_error("Unable to move from Python "
1259                          + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1260                          + type_id<T>() + " instance: instance has multiple references");
1261 #endif
1262     }
1263 
1264     // Move into a temporary and return that, because the reference may be a local value of `conv`
1265     T ret = std::move(detail::load_type<T>(obj).operator T &());
1266     return ret;
1267 }
1268 
1269 // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1270 // - If we have to move (because T has no copy constructor), do it.  This will fail if the moved
1271 //   object has multiple references, but trying to copy will fail to compile.
1272 // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1273 // - Otherwise (not movable), copy.
1274 template <typename T>
1275 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1276 cast(object &&object) {
1277     return move<T>(std::move(object));
1278 }
1279 template <typename T>
1280 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1281 cast(object &&object) {
1282     if (object.ref_count() > 1) {
1283         return cast<T>(object);
1284     }
1285     return move<T>(std::move(object));
1286 }
1287 template <typename T>
1288 detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1289 cast(object &&object) {
1290     return cast<T>(object);
1291 }
1292 
1293 // pytype rvalue -> pytype (calls converting constructor)
1294 template <typename T>
1295 detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1296     return T(std::move(object));
1297 }
1298 
1299 template <typename T>
1300 T object::cast() const & {
1301     return pybind11::cast<T>(*this);
1302 }
1303 template <typename T>
1304 T object::cast() && {
1305     return pybind11::cast<T>(std::move(*this));
1306 }
1307 template <>
1308 inline void object::cast() const & {
1309     return;
1310 }
1311 template <>
1312 inline void object::cast() && {
1313     return;
1314 }
1315 
1316 PYBIND11_NAMESPACE_BEGIN(detail)
1317 
1318 // Declared in pytypes.h:
1319 template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1320 object object_or_cast(T &&o) {
1321     return pybind11::cast(std::forward<T>(o));
1322 }
1323 
1324 // Placeholder type for the unneeded (and dead code) static variable in the
1325 // PYBIND11_OVERRIDE_OVERRIDE macro
1326 struct override_unused {};
1327 template <typename ret_type>
1328 using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1329                                         make_caster<ret_type>,
1330                                         override_unused>;
1331 
1332 // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1333 // store the result in the given variable.  For other types, this is a no-op.
1334 template <typename T>
1335 enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1336                                                                      make_caster<T> &caster) {
1337     return cast_op<T>(load_type(caster, o));
1338 }
1339 template <typename T>
1340 enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1341                                                                       override_unused &) {
1342     pybind11_fail("Internal error: cast_ref fallback invoked");
1343 }
1344 
1345 // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1346 // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1347 // that only does anything in cases where pybind11::cast is valid.
1348 template <typename T>
1349 enable_if_t<cast_is_temporary_value_reference<T>::value
1350                 && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1351             T>
1352 cast_safe(object &&) {
1353     pybind11_fail("Internal error: cast_safe fallback invoked");
1354 }
1355 template <typename T>
1356 enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1357 template <typename T>
1358 enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1359 cast_safe(object &&o) {
1360     return o.release().ptr();
1361 }
1362 template <typename T>
1363 enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1364                             detail::is_same_ignoring_cvref<T, PyObject *>,
1365                             std::is_void<T>>::value,
1366             T>
1367 cast_safe(object &&o) {
1368     return pybind11::cast<T>(std::move(o));
1369 }
1370 
1371 PYBIND11_NAMESPACE_END(detail)
1372 
1373 // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1374 // but it is an easy minor optimization.
1375 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1376 inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1377     return cast_error("Unable to convert call argument '" + name
1378                       + "' to Python object (#define "
1379                         "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1380 }
1381 #else
1382 inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1383                                                         const std::string &type) {
1384     return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1385                       + "' to Python object");
1386 }
1387 #endif
1388 
1389 template <return_value_policy policy = return_value_policy::automatic_reference>
1390 tuple make_tuple() {
1391     return tuple(0);
1392 }
1393 
1394 template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1395 tuple make_tuple(Args &&...args_) {
1396     constexpr size_t size = sizeof...(Args);
1397     std::array<object, size> args{{reinterpret_steal<object>(
1398         detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1399     for (size_t i = 0; i < args.size(); i++) {
1400         if (!args[i]) {
1401 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1402             throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1403 #else
1404             std::array<std::string, size> argtypes{{type_id<Args>()...}};
1405             throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1406 #endif
1407         }
1408     }
1409     tuple result(size);
1410     int counter = 0;
1411     for (auto &arg_value : args) {
1412         PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1413     }
1414     return result;
1415 }
1416 
1417 /// \ingroup annotations
1418 /// Annotation for arguments
1419 struct arg {
1420     /// Constructs an argument with the name of the argument; if null or omitted, this is a
1421     /// positional argument.
1422     constexpr explicit arg(const char *name = nullptr)
1423         : name(name), flag_noconvert(false), flag_none(true) {}
1424     /// Assign a value to this argument
1425     template <typename T>
1426     arg_v operator=(T &&value) const;
1427     /// Indicate that the type should not be converted in the type caster
1428     arg &noconvert(bool flag = true) {
1429         flag_noconvert = flag;
1430         return *this;
1431     }
1432     /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1433     arg &none(bool flag = true) {
1434         flag_none = flag;
1435         return *this;
1436     }
1437 
1438     const char *name;        ///< If non-null, this is a named kwargs argument
1439     bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1440                              ///< caster!)
1441     bool flag_none : 1;      ///< If set (the default), allow None to be passed to this argument
1442 };
1443 
1444 /// \ingroup annotations
1445 /// Annotation for arguments with values
1446 struct arg_v : arg {
1447 private:
1448     template <typename T>
1449     arg_v(arg &&base, T &&x, const char *descr = nullptr)
1450         : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1451                          std::forward<T>(x), return_value_policy::automatic, {}))),
1452           descr(descr)
1453 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1454           ,
1455           type(type_id<T>())
1456 #endif
1457     {
1458         // Workaround! See:
1459         // https://github.com/pybind/pybind11/issues/2336
1460         // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1461         if (PyErr_Occurred()) {
1462             PyErr_Clear();
1463         }
1464     }
1465 
1466 public:
1467     /// Direct construction with name, default, and description
1468     template <typename T>
1469     arg_v(const char *name, T &&x, const char *descr = nullptr)
1470         : arg_v(arg(name), std::forward<T>(x), descr) {}
1471 
1472     /// Called internally when invoking `py::arg("a") = value`
1473     template <typename T>
1474     arg_v(const arg &base, T &&x, const char *descr = nullptr)
1475         : arg_v(arg(base), std::forward<T>(x), descr) {}
1476 
1477     /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1478     arg_v &noconvert(bool flag = true) {
1479         arg::noconvert(flag);
1480         return *this;
1481     }
1482 
1483     /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1484     arg_v &none(bool flag = true) {
1485         arg::none(flag);
1486         return *this;
1487     }
1488 
1489     /// The default value
1490     object value;
1491     /// The (optional) description of the default value
1492     const char *descr;
1493 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1494     /// The C++ type name of the default value (only available when compiled in debug mode)
1495     std::string type;
1496 #endif
1497 };
1498 
1499 /// \ingroup annotations
1500 /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
1501 /// an unnamed '*' argument
1502 struct kw_only {};
1503 
1504 /// \ingroup annotations
1505 /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
1506 /// an unnamed '/' argument (in Python 3.8)
1507 struct pos_only {};
1508 
1509 template <typename T>
1510 arg_v arg::operator=(T &&value) const {
1511     return {*this, std::forward<T>(value)};
1512 }
1513 
1514 /// Alias for backward compatibility -- to be removed in version 2.0
1515 template <typename /*unused*/>
1516 using arg_t = arg_v;
1517 
1518 inline namespace literals {
1519 /** \rst
1520     String literal version of `arg`
1521  \endrst */
1522 constexpr arg
1523 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1524 operator"" _a // gcc 4.8.5 insists on having a space (hard error).
1525 #else
1526 operator""_a // clang 17 generates a deprecation warning if there is a space.
1527 #endif
1528     (const char *name, size_t) {
1529     return arg(name);
1530 }
1531 } // namespace literals
1532 
1533 PYBIND11_NAMESPACE_BEGIN(detail)
1534 
1535 template <typename T>
1536 using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1537 template <typename T>
1538 using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1539 
1540 // forward declaration (definition in attr.h)
1541 struct function_record;
1542 
1543 /// Internal data associated with a single function call
1544 struct function_call {
1545     function_call(const function_record &f, handle p); // Implementation in attr.h
1546 
1547     /// The function data:
1548     const function_record &func;
1549 
1550     /// Arguments passed to the function:
1551     std::vector<handle> args;
1552 
1553     /// The `convert` value the arguments should be loaded with
1554     std::vector<bool> args_convert;
1555 
1556     /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
1557     /// present, are also in `args` but without a reference).
1558     object args_ref, kwargs_ref;
1559 
1560     /// The parent, if any
1561     handle parent;
1562 
1563     /// If this is a call to an initializer, this argument contains `self`
1564     handle init_self;
1565 };
1566 
1567 /// Helper class which loads arguments for C++ functions called from Python
1568 template <typename... Args>
1569 class argument_loader {
1570     using indices = make_index_sequence<sizeof...(Args)>;
1571 
1572     template <typename Arg>
1573     using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1574     template <typename Arg>
1575     using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1576     // Get kwargs argument position, or -1 if not present:
1577     static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1578 
1579     static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1580                   "py::kwargs is only permitted as the last argument of a function");
1581 
1582 public:
1583     static constexpr bool has_kwargs = kwargs_pos != -1;
1584 
1585     // py::args argument position; -1 if not present.
1586     static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1587 
1588     static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1589                   "py::args cannot be specified more than once");
1590 
1591     static constexpr auto arg_names
1592         = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
1593 
1594     bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
1595 
1596     template <typename Return, typename Guard, typename Func>
1597     // NOLINTNEXTLINE(readability-const-return-type)
1598     enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1599         return std::move(*this).template call_impl<remove_cv_t<Return>>(
1600             std::forward<Func>(f), indices{}, Guard{});
1601     }
1602 
1603     template <typename Return, typename Guard, typename Func>
1604     enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1605         std::move(*this).template call_impl<remove_cv_t<Return>>(
1606             std::forward<Func>(f), indices{}, Guard{});
1607         return void_type();
1608     }
1609 
1610 private:
1611     static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1612 
1613     template <size_t... Is>
1614     bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1615 #ifdef __cpp_fold_expressions
1616         if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1617             return false;
1618         }
1619 #else
1620         for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1621             if (!r) {
1622                 return false;
1623             }
1624         }
1625 #endif
1626         return true;
1627     }
1628 
1629     template <typename Return, typename Func, size_t... Is, typename Guard>
1630     Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1631         return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1632     }
1633 
1634     std::tuple<make_caster<Args>...> argcasters;
1635 };
1636 
1637 /// Helper class which collects only positional arguments for a Python function call.
1638 /// A fancier version below can collect any argument, but this one is optimal for simple calls.
1639 template <return_value_policy policy>
1640 class simple_collector {
1641 public:
1642     template <typename... Ts>
1643     explicit simple_collector(Ts &&...values)
1644         : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1645 
1646     const tuple &args() const & { return m_args; }
1647     dict kwargs() const { return {}; }
1648 
1649     tuple args() && { return std::move(m_args); }
1650 
1651     /// Call a Python function and pass the collected arguments
1652     object call(PyObject *ptr) const {
1653         PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1654         if (!result) {
1655             throw error_already_set();
1656         }
1657         return reinterpret_steal<object>(result);
1658     }
1659 
1660 private:
1661     tuple m_args;
1662 };
1663 
1664 /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
1665 template <return_value_policy policy>
1666 class unpacking_collector {
1667 public:
1668     template <typename... Ts>
1669     explicit unpacking_collector(Ts &&...values) {
1670         // Tuples aren't (easily) resizable so a list is needed for collection,
1671         // but the actual function call strictly requires a tuple.
1672         auto args_list = list();
1673         using expander = int[];
1674         (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1675 
1676         m_args = std::move(args_list);
1677     }
1678 
1679     const tuple &args() const & { return m_args; }
1680     const dict &kwargs() const & { return m_kwargs; }
1681 
1682     tuple args() && { return std::move(m_args); }
1683     dict kwargs() && { return std::move(m_kwargs); }
1684 
1685     /// Call a Python function and pass the collected arguments
1686     object call(PyObject *ptr) const {
1687         PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1688         if (!result) {
1689             throw error_already_set();
1690         }
1691         return reinterpret_steal<object>(result);
1692     }
1693 
1694 private:
1695     template <typename T>
1696     void process(list &args_list, T &&x) {
1697         auto o = reinterpret_steal<object>(
1698             detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1699         if (!o) {
1700 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1701             throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
1702 #else
1703             throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1704                                                         type_id<T>());
1705 #endif
1706         }
1707         args_list.append(std::move(o));
1708     }
1709 
1710     void process(list &args_list, detail::args_proxy ap) {
1711         for (auto a : ap) {
1712             args_list.append(a);
1713         }
1714     }
1715 
1716     void process(list & /*args_list*/, arg_v a) {
1717         if (!a.name) {
1718 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1719             nameless_argument_error();
1720 #else
1721             nameless_argument_error(a.type);
1722 #endif
1723         }
1724         if (m_kwargs.contains(a.name)) {
1725 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1726             multiple_values_error();
1727 #else
1728             multiple_values_error(a.name);
1729 #endif
1730         }
1731         if (!a.value) {
1732 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1733             throw cast_error_unable_to_convert_call_arg(a.name);
1734 #else
1735             throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1736 #endif
1737         }
1738         m_kwargs[a.name] = std::move(a.value);
1739     }
1740 
1741     void process(list & /*args_list*/, detail::kwargs_proxy kp) {
1742         if (!kp) {
1743             return;
1744         }
1745         for (auto k : reinterpret_borrow<dict>(kp)) {
1746             if (m_kwargs.contains(k.first)) {
1747 #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1748                 multiple_values_error();
1749 #else
1750                 multiple_values_error(str(k.first));
1751 #endif
1752             }
1753             m_kwargs[k.first] = k.second;
1754         }
1755     }
1756 
1757     [[noreturn]] static void nameless_argument_error() {
1758         throw type_error(
1759             "Got kwargs without a name; only named arguments "
1760             "may be passed via py::arg() to a python function call. "
1761             "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1762     }
1763     [[noreturn]] static void nameless_argument_error(const std::string &type) {
1764         throw type_error("Got kwargs without a name of type '" + type
1765                          + "'; only named "
1766                            "arguments may be passed via py::arg() to a python function call. ");
1767     }
1768     [[noreturn]] static void multiple_values_error() {
1769         throw type_error(
1770             "Got multiple values for keyword argument "
1771             "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1772     }
1773 
1774     [[noreturn]] static void multiple_values_error(const std::string &name) {
1775         throw type_error("Got multiple values for keyword argument '" + name + "'");
1776     }
1777 
1778 private:
1779     tuple m_args;
1780     dict m_kwargs;
1781 };
1782 
1783 // [workaround(intel)] Separate function required here
1784 // We need to put this into a separate function because the Intel compiler
1785 // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1786 // (tested with ICC 2021.1 Beta 20200827).
1787 template <typename... Args>
1788 constexpr bool args_are_all_positional() {
1789     return all_of<is_positional<Args>...>::value;
1790 }
1791 
1792 /// Collect only positional arguments for a Python function call
1793 template <return_value_policy policy,
1794           typename... Args,
1795           typename = enable_if_t<args_are_all_positional<Args...>()>>
1796 simple_collector<policy> collect_arguments(Args &&...args) {
1797     return simple_collector<policy>(std::forward<Args>(args)...);
1798 }
1799 
1800 /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
1801 template <return_value_policy policy,
1802           typename... Args,
1803           typename = enable_if_t<!args_are_all_positional<Args...>()>>
1804 unpacking_collector<policy> collect_arguments(Args &&...args) {
1805     // Following argument order rules for generalized unpacking according to PEP 448
1806     static_assert(constexpr_last<is_positional, Args...>()
1807                           < constexpr_first<is_keyword_or_ds, Args...>()
1808                       && constexpr_last<is_s_unpacking, Args...>()
1809                              < constexpr_first<is_ds_unpacking, Args...>(),
1810                   "Invalid function call: positional args must precede keywords and ** unpacking; "
1811                   "* unpacking must precede ** unpacking");
1812     return unpacking_collector<policy>(std::forward<Args>(args)...);
1813 }
1814 
1815 template <typename Derived>
1816 template <return_value_policy policy, typename... Args>
1817 object object_api<Derived>::operator()(Args &&...args) const {
1818 #ifndef NDEBUG
1819     if (!PyGILState_Check()) {
1820         pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1821     }
1822 #endif
1823     return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1824 }
1825 
1826 template <typename Derived>
1827 template <return_value_policy policy, typename... Args>
1828 object object_api<Derived>::call(Args &&...args) const {
1829     return operator()<policy>(std::forward<Args>(args)...);
1830 }
1831 
1832 PYBIND11_NAMESPACE_END(detail)
1833 
1834 template <typename T>
1835 handle type::handle_of() {
1836     static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1837                   "py::type::of<T> only supports the case where T is a registered C++ types.");
1838 
1839     return detail::get_type_handle(typeid(T), true);
1840 }
1841 
1842 #define PYBIND11_MAKE_OPAQUE(...)                                                                 \
1843     PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)                                                  \
1844     namespace detail {                                                                            \
1845     template <>                                                                                   \
1846     class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {};                     \
1847     }                                                                                             \
1848     PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1849 
1850 /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
1851 /// typedef, e.g.:
1852 /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
1853 #define PYBIND11_TYPE(...) __VA_ARGS__
1854 
1855 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)