File indexing completed on 2025-02-16 05:12:13

0001 /*
0002     pybind11/detail/common.h -- Basic macros
0003 
0004     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #pragma once
0011 
0012 #define PYBIND11_VERSION_MAJOR 2
0013 #define PYBIND11_VERSION_MINOR 9
0014 #define PYBIND11_VERSION_PATCH 1
0015 
0016 // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
0017 // Additional convention: 0xD = dev
0018 #define PYBIND11_VERSION_HEX 0x02090100
0019 
0020 #define PYBIND11_NAMESPACE_BEGIN(name) namespace name {
0021 #define PYBIND11_NAMESPACE_END(name) }
0022 
0023 // Robust support for some features and loading modules compiled against different pybind versions
0024 // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
0025 // the main `pybind11` namespace.
0026 #if !defined(PYBIND11_NAMESPACE)
0027 #  ifdef __GNUG__
0028 #    define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
0029 #  else
0030 #    define PYBIND11_NAMESPACE pybind11
0031 #  endif
0032 #endif
0033 
0034 #if !(defined(_MSC_VER) && __cplusplus == 199711L)
0035 #  if __cplusplus >= 201402L
0036 #    define PYBIND11_CPP14
0037 #    if __cplusplus >= 201703L
0038 #      define PYBIND11_CPP17
0039 #      if __cplusplus >= 202002L
0040 #        define PYBIND11_CPP20
0041 #      endif
0042 #    endif
0043 #  endif
0044 #elif defined(_MSC_VER) && __cplusplus == 199711L
0045 // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
0046 // Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
0047 #  if _MSVC_LANG >= 201402L
0048 #    define PYBIND11_CPP14
0049 #    if _MSVC_LANG > 201402L && _MSC_VER >= 1910
0050 #      define PYBIND11_CPP17
0051 #      if _MSVC_LANG >= 202002L
0052 #        define PYBIND11_CPP20
0053 #      endif
0054 #    endif
0055 #  endif
0056 #endif
0057 
0058 // Compiler version assertions
0059 #if defined(__INTEL_COMPILER)
0060 #  if __INTEL_COMPILER < 1800
0061 #    error pybind11 requires Intel C++ compiler v18 or newer
0062 #  elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
0063 #    error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
0064 #  endif
0065 /* The following pragma cannot be pop'ed:
0066    https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
0067 #  pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
0068 #elif defined(__clang__) && !defined(__apple_build_version__)
0069 #  if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
0070 #    error pybind11 requires clang 3.3 or newer
0071 #  endif
0072 #elif defined(__clang__)
0073 // Apple changes clang version macros to its Xcode version; the first Xcode release based on
0074 // (upstream) clang 3.3 was Xcode 5:
0075 #  if __clang_major__ < 5
0076 #    error pybind11 requires Xcode/clang 5.0 or newer
0077 #  endif
0078 #elif defined(__GNUG__)
0079 #  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
0080 #    error pybind11 requires gcc 4.8 or newer
0081 #  endif
0082 #elif defined(_MSC_VER)
0083 // Pybind hits various compiler bugs in 2015u2 and earlier, and also makes use of some stl features
0084 // (e.g. std::negation) added in 2015u3:
0085 #  if _MSC_FULL_VER < 190024210
0086 #    error pybind11 requires MSVC 2015 update 3 or newer
0087 #  endif
0088 #endif
0089 
0090 #if !defined(PYBIND11_EXPORT)
0091 #  if defined(WIN32) || defined(_WIN32)
0092 #    define PYBIND11_EXPORT __declspec(dllexport)
0093 #  else
0094 #    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
0095 #  endif
0096 #endif
0097 
0098 #if !defined(PYBIND11_EXPORT_EXCEPTION)
0099 #  ifdef __MINGW32__
0100 // workaround for:
0101 // error: 'dllexport' implies default visibility, but xxx has already been declared with a different visibility
0102 #    define PYBIND11_EXPORT_EXCEPTION
0103 #  else
0104 #    define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
0105 #  endif
0106 #endif
0107 
0108 // For CUDA, GCC7, GCC8:
0109 // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
0110 // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
0111 // However, the measured shared-library size saving when using noinline are only
0112 // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
0113 // the default under pybind11/tests).
0114 #if !defined(PYBIND11_NOINLINE_FORCED) && \
0115     (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
0116 #  define PYBIND11_NOINLINE_DISABLED
0117 #endif
0118 
0119 // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
0120 // In contrast, FORWARD DECLARATIONS should never use this macro:
0121 // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
0122 #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
0123 #  define PYBIND11_NOINLINE inline
0124 #elif defined(_MSC_VER)
0125 #  define PYBIND11_NOINLINE __declspec(noinline) inline
0126 #else
0127 #  define PYBIND11_NOINLINE __attribute__ ((noinline)) inline
0128 #endif
0129 
0130 #if defined(__MINGW32__)
0131 // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
0132 // whether it is used or not
0133 #  define PYBIND11_DEPRECATED(reason)
0134 #elif defined(PYBIND11_CPP14)
0135 #  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
0136 #else
0137 #  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
0138 #endif
0139 
0140 #if defined(PYBIND11_CPP17)
0141 #  define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
0142 #elif defined(_MSC_VER) && !defined(__clang__)
0143 #  define PYBIND11_MAYBE_UNUSED
0144 #else
0145 #  define PYBIND11_MAYBE_UNUSED __attribute__ ((__unused__))
0146 #endif
0147 
0148 /* Don't let Python.h #define (v)snprintf as macro because they are implemented
0149    properly in Visual Studio since 2015. */
0150 #if defined(_MSC_VER) && _MSC_VER >= 1900
0151 #  define HAVE_SNPRINTF 1
0152 #endif
0153 
0154 /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
0155 #if defined(_MSC_VER)
0156 #  if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 4)
0157 #    define HAVE_ROUND 1
0158 #  endif
0159 #  pragma warning(push)
0160 // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
0161 #  pragma warning(disable: 4505)
0162 #  if defined(_DEBUG) && !defined(Py_DEBUG)
0163 // Workaround for a VS 2022 issue.
0164 // NOTE: This workaround knowingly violates the Python.h include order requirement:
0165 // https://docs.python.org/3/c-api/intro.html#include-files
0166 // See https://github.com/pybind/pybind11/pull/3497 for full context.
0167 #    include <yvals.h>
0168 #    if _MSVC_STL_VERSION >= 143
0169 #      include <crtdefs.h>
0170 #    endif
0171 #    define PYBIND11_DEBUG_MARKER
0172 #    undef _DEBUG
0173 #  endif
0174 #endif
0175 
0176 // https://en.cppreference.com/w/c/chrono/localtime
0177 #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
0178 #  define __STDC_WANT_LIB_EXT1__
0179 #endif
0180 
0181 #ifdef __has_include
0182 // std::optional (but including it in c++14 mode isn't allowed)
0183 #  if defined(PYBIND11_CPP17) && __has_include(<optional>)
0184 #    define PYBIND11_HAS_OPTIONAL 1
0185 #  endif
0186 // std::experimental::optional (but not allowed in c++11 mode)
0187 #  if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
0188                                  !__has_include(<optional>))
0189 #    define PYBIND11_HAS_EXP_OPTIONAL 1
0190 #  endif
0191 // std::variant
0192 #  if defined(PYBIND11_CPP17) && __has_include(<variant>)
0193 #    define PYBIND11_HAS_VARIANT 1
0194 #  endif
0195 #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
0196 #  define PYBIND11_HAS_OPTIONAL 1
0197 #  define PYBIND11_HAS_VARIANT 1
0198 #endif
0199 
0200 #if defined(PYBIND11_CPP17)
0201 #  if defined(__has_include)
0202 #    if __has_include(<string_view>)
0203 #      define PYBIND11_HAS_STRING_VIEW
0204 #    endif
0205 #  elif defined(_MSC_VER)
0206 #    define PYBIND11_HAS_STRING_VIEW
0207 #  endif
0208 #endif
0209 
0210 #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
0211 #  define PYBIND11_HAS_U8STRING
0212 #endif
0213 
0214 
0215 #include <Python.h>
0216 #include <frameobject.h>
0217 #include <pythread.h>
0218 
0219 /* Python #defines overrides on all sorts of core functions, which
0220    tends to weak havok in C++ codebases that expect these to work
0221    like regular functions (potentially with several overloads) */
0222 #if defined(isalnum)
0223 #  undef isalnum
0224 #  undef isalpha
0225 #  undef islower
0226 #  undef isspace
0227 #  undef isupper
0228 #  undef tolower
0229 #  undef toupper
0230 #endif
0231 
0232 #if defined(copysign)
0233 #  undef copysign
0234 #endif
0235 
0236 #if defined(_MSC_VER)
0237 #  if defined(PYBIND11_DEBUG_MARKER)
0238 #    define _DEBUG
0239 #    undef PYBIND11_DEBUG_MARKER
0240 #  endif
0241 #  pragma warning(pop)
0242 #endif
0243 
0244 #include <cstddef>
0245 #include <cstring>
0246 #include <forward_list>
0247 #include <vector>
0248 #include <string>
0249 #include <stdexcept>
0250 #include <exception>
0251 #include <unordered_set>
0252 #include <unordered_map>
0253 #include <memory>
0254 #include <typeindex>
0255 #include <type_traits>
0256 #if defined(__has_include)
0257 #  if __has_include(<version>)
0258 #    include <version>
0259 #  endif
0260 #endif
0261 
0262 // #define PYBIND11_STR_LEGACY_PERMISSIVE
0263 // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
0264 //             (probably surprising and never documented, but this was the
0265 //             legacy behavior until and including v2.6.x). As a side-effect,
0266 //             pybind11::isinstance<str>() is true for both pybind11::str and
0267 //             pybind11::bytes.
0268 // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
0269 //               pybind11::isinstance<str>() is true only for pybind11::str.
0270 //               However, for Python 2 only (!), the pybind11::str caster
0271 //               implicitly decodes bytes to PyUnicodeObject. This is to ease
0272 //               the transition from the legacy behavior to the non-permissive
0273 //               behavior.
0274 
0275 #if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
0276 #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
0277 #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
0278 #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
0279 #define PYBIND11_BYTES_CHECK PyBytes_Check
0280 #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
0281 #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
0282 #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
0283 #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
0284 #define PYBIND11_BYTES_SIZE PyBytes_Size
0285 #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
0286 #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
0287 #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
0288 #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
0289 #define PYBIND11_BYTES_NAME "bytes"
0290 #define PYBIND11_STRING_NAME "str"
0291 #define PYBIND11_SLICE_OBJECT PyObject
0292 #define PYBIND11_FROM_STRING PyUnicode_FromString
0293 #define PYBIND11_STR_TYPE ::pybind11::str
0294 #define PYBIND11_BOOL_ATTR "__bool__"
0295 #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
0296 #define PYBIND11_BUILTINS_MODULE "builtins"
0297 // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
0298 // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
0299 #define PYBIND11_PLUGIN_IMPL(name) \
0300     extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
0301     extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
0302 
0303 #else
0304 #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
0305 #define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
0306 #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
0307 #define PYBIND11_BYTES_CHECK PyString_Check
0308 #define PYBIND11_BYTES_FROM_STRING PyString_FromString
0309 #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
0310 #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
0311 #define PYBIND11_BYTES_AS_STRING PyString_AsString
0312 #define PYBIND11_BYTES_SIZE PyString_Size
0313 #define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
0314 #define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
0315 #define PYBIND11_LONG_FROM_SIGNED(o) PyInt_FromSsize_t((ssize_t) o) // Returns long if needed.
0316 #define PYBIND11_LONG_FROM_UNSIGNED(o) PyInt_FromSize_t((size_t) o) // Returns long if needed.
0317 #define PYBIND11_BYTES_NAME "str"
0318 #define PYBIND11_STRING_NAME "unicode"
0319 #define PYBIND11_SLICE_OBJECT PySliceObject
0320 #define PYBIND11_FROM_STRING PyString_FromString
0321 #define PYBIND11_STR_TYPE ::pybind11::bytes
0322 #define PYBIND11_BOOL_ATTR "__nonzero__"
0323 #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_nonzero)
0324 #define PYBIND11_BUILTINS_MODULE "__builtin__"
0325 // Providing a separate PyInit decl to make Clang's -Wmissing-prototypes happy.
0326 // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
0327 #define PYBIND11_PLUGIN_IMPL(name) \
0328     static PyObject *pybind11_init_wrapper();                           \
0329     extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT void init##name(); \
0330     extern "C" PYBIND11_EXPORT void init##name() {                      \
0331         (void)pybind11_init_wrapper();                                  \
0332     }                                                                   \
0333     PyObject *pybind11_init_wrapper()
0334 #endif
0335 
0336 #if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
0337 extern "C" {
0338     struct _Py_atomic_address { void *value; };
0339     PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
0340 }
0341 #endif
0342 
0343 #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
0344 #define PYBIND11_STRINGIFY(x) #x
0345 #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
0346 #define PYBIND11_CONCAT(first, second) first##second
0347 #define PYBIND11_ENSURE_INTERNALS_READY \
0348     pybind11::detail::get_internals();
0349 
0350 #define PYBIND11_CHECK_PYTHON_VERSION \
0351     {                                                                          \
0352         const char *compiled_ver = PYBIND11_TOSTRING(PY_MAJOR_VERSION)         \
0353             "." PYBIND11_TOSTRING(PY_MINOR_VERSION);                           \
0354         const char *runtime_ver = Py_GetVersion();                             \
0355         size_t len = std::strlen(compiled_ver);                                \
0356         if (std::strncmp(runtime_ver, compiled_ver, len) != 0                  \
0357                 || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) {     \
0358             PyErr_Format(PyExc_ImportError,                                    \
0359                 "Python version mismatch: module was compiled for Python %s, " \
0360                 "but the interpreter version is incompatible: %s.",            \
0361                 compiled_ver, runtime_ver);                                    \
0362             return nullptr;                                                    \
0363         }                                                                      \
0364     }
0365 
0366 #if PY_VERSION_HEX >= 0x03030000
0367 
0368 #define PYBIND11_CATCH_INIT_EXCEPTIONS \
0369         catch (pybind11::error_already_set &e) {                                 \
0370             pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
0371             return nullptr;                                                      \
0372         } catch (const std::exception &e) {                                      \
0373             PyErr_SetString(PyExc_ImportError, e.what());                        \
0374             return nullptr;                                                      \
0375         }                                                                        \
0376 
0377 #else
0378 
0379 #define PYBIND11_CATCH_INIT_EXCEPTIONS \
0380         catch (pybind11::error_already_set &e) {                               \
0381             PyErr_SetString(PyExc_ImportError, e.what());                      \
0382             return nullptr;                                                    \
0383         } catch (const std::exception &e) {                                    \
0384             PyErr_SetString(PyExc_ImportError, e.what());                      \
0385             return nullptr;                                                    \
0386         }                                                                      \
0387 
0388 #endif
0389 
0390 /** \rst
0391     ***Deprecated in favor of PYBIND11_MODULE***
0392 
0393     This macro creates the entry point that will be invoked when the Python interpreter
0394     imports a plugin library. Please create a `module_` in the function body and return
0395     the pointer to its underlying Python object at the end.
0396 
0397     .. code-block:: cpp
0398 
0399         PYBIND11_PLUGIN(example) {
0400             pybind11::module_ m("example", "pybind11 example plugin");
0401             /// Set up bindings here
0402             return m.ptr();
0403         }
0404 \endrst */
0405 #define PYBIND11_PLUGIN(name)                                                  \
0406     PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE")  \
0407     static PyObject *pybind11_init();                                          \
0408     PYBIND11_PLUGIN_IMPL(name) {                                               \
0409         PYBIND11_CHECK_PYTHON_VERSION                                          \
0410         PYBIND11_ENSURE_INTERNALS_READY                                        \
0411         try {                                                                  \
0412             return pybind11_init();                                            \
0413         } PYBIND11_CATCH_INIT_EXCEPTIONS                                       \
0414     }                                                                          \
0415     PyObject *pybind11_init()
0416 
0417 /** \rst
0418     This macro creates the entry point that will be invoked when the Python interpreter
0419     imports an extension module. The module name is given as the fist argument and it
0420     should not be in quotes. The second macro argument defines a variable of type
0421     `py::module_` which can be used to initialize the module.
0422 
0423     The entry point is marked as "maybe unused" to aid dead-code detection analysis:
0424     since the entry point is typically only looked up at runtime and not referenced
0425     during translation, it would otherwise appear as unused ("dead") code.
0426 
0427     .. code-block:: cpp
0428 
0429         PYBIND11_MODULE(example, m) {
0430             m.doc() = "pybind11 example module";
0431 
0432             // Add bindings here
0433             m.def("foo", []() {
0434                 return "Hello, World!";
0435             });
0436         }
0437 \endrst */
0438 #define PYBIND11_MODULE(name, variable)                                                           \
0439     static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name)            \
0440         PYBIND11_MAYBE_UNUSED;                                                                    \
0441     PYBIND11_MAYBE_UNUSED                                                                         \
0442     static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &);                     \
0443     PYBIND11_PLUGIN_IMPL(name) {                                                                  \
0444         PYBIND11_CHECK_PYTHON_VERSION                                                             \
0445         PYBIND11_ENSURE_INTERNALS_READY                                                           \
0446         auto m = ::pybind11::module_::create_extension_module(                                    \
0447             PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name));      \
0448         try {                                                                                     \
0449             PYBIND11_CONCAT(pybind11_init_, name)(m);                                             \
0450             return m.ptr();                                                                       \
0451         }                                                                                         \
0452         PYBIND11_CATCH_INIT_EXCEPTIONS                                                            \
0453     }                                                                                             \
0454     void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
0455 
0456 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0457 
0458 using ssize_t = Py_ssize_t;
0459 using size_t  = std::size_t;
0460 
0461 template <typename IntType>
0462 inline ssize_t ssize_t_cast(const IntType &val) {
0463     static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
0464     return static_cast<ssize_t>(val);
0465 }
0466 
0467 /// Approach used to cast a previously unknown C++ instance into a Python object
0468 enum class return_value_policy : uint8_t {
0469     /** This is the default return value policy, which falls back to the policy
0470         return_value_policy::take_ownership when the return value is a pointer.
0471         Otherwise, it uses return_value::move or return_value::copy for rvalue
0472         and lvalue references, respectively. See below for a description of what
0473         all of these different policies do. */
0474     automatic = 0,
0475 
0476     /** As above, but use policy return_value_policy::reference when the return
0477         value is a pointer. This is the default conversion policy for function
0478         arguments when calling Python functions manually from C++ code (i.e. via
0479         handle::operator()). You probably won't need to use this. */
0480     automatic_reference,
0481 
0482     /** Reference an existing object (i.e. do not create a new copy) and take
0483         ownership. Python will call the destructor and delete operator when the
0484         object’s reference count reaches zero. Undefined behavior ensues when
0485         the C++ side does the same.. */
0486     take_ownership,
0487 
0488     /** Create a new copy of the returned object, which will be owned by
0489         Python. This policy is comparably safe because the lifetimes of the two
0490         instances are decoupled. */
0491     copy,
0492 
0493     /** Use std::move to move the return value contents into a new instance
0494         that will be owned by Python. This policy is comparably safe because the
0495         lifetimes of the two instances (move source and destination) are
0496         decoupled. */
0497     move,
0498 
0499     /** Reference an existing object, but do not take ownership. The C++ side
0500         is responsible for managing the object’s lifetime and deallocating it
0501         when it is no longer used. Warning: undefined behavior will ensue when
0502         the C++ side deletes an object that is still referenced and used by
0503         Python. */
0504     reference,
0505 
0506     /** This policy only applies to methods and properties. It references the
0507         object without taking ownership similar to the above
0508         return_value_policy::reference policy. In contrast to that policy, the
0509         function or property’s implicit this argument (called the parent) is
0510         considered to be the the owner of the return value (the child).
0511         pybind11 then couples the lifetime of the parent to the child via a
0512         reference relationship that ensures that the parent cannot be garbage
0513         collected while Python is still using the child. More advanced
0514         variations of this scheme are also possible using combinations of
0515         return_value_policy::reference and the keep_alive call policy */
0516     reference_internal
0517 };
0518 
0519 PYBIND11_NAMESPACE_BEGIN(detail)
0520 
0521 inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
0522 
0523 // Returns the size as a multiple of sizeof(void *), rounded up.
0524 inline static constexpr size_t size_in_ptrs(size_t s) { return 1 + ((s - 1) >> log2(sizeof(void *))); }
0525 
0526 /**
0527  * The space to allocate for simple layout instance holders (see below) in multiple of the size of
0528  * a pointer (e.g.  2 means 16 bytes on 64-bit architectures).  The default is the minimum required
0529  * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
0530  * sizeof(std::shared_ptr<T>)).
0531  */
0532 constexpr size_t instance_simple_holder_in_ptrs() {
0533     static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
0534             "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
0535     return size_in_ptrs(sizeof(std::shared_ptr<int>));
0536 }
0537 
0538 // Forward declarations
0539 struct type_info;
0540 struct value_and_holder;
0541 
0542 struct nonsimple_values_and_holders {
0543     void **values_and_holders;
0544     uint8_t *status;
0545 };
0546 
0547 /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
0548 struct instance {
0549     PyObject_HEAD
0550     /// Storage for pointers and holder; see simple_layout, below, for a description
0551     union {
0552         void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
0553         nonsimple_values_and_holders nonsimple;
0554     };
0555     /// Weak references
0556     PyObject *weakrefs;
0557     /// If true, the pointer is owned which means we're free to manage it with a holder.
0558     bool owned : 1;
0559     /**
0560      * An instance has two possible value/holder layouts.
0561      *
0562      * Simple layout (when this flag is true), means the `simple_value_holder` is set with a pointer
0563      * and the holder object governing that pointer, i.e. [val1*][holder].  This layout is applied
0564      * whenever there is no python-side multiple inheritance of bound C++ types *and* the type's
0565      * holder will fit in the default space (which is large enough to hold either a std::unique_ptr
0566      * or std::shared_ptr).
0567      *
0568      * Non-simple layout applies when using custom holders that require more space than `shared_ptr`
0569      * (which is typically the size of two pointers), or when multiple inheritance is used on the
0570      * python side.  Non-simple layout allocates the required amount of memory to have multiple
0571      * bound C++ classes as parents.  Under this layout, `nonsimple.values_and_holders` is set to a
0572      * pointer to allocated space of the required space to hold a sequence of value pointers and
0573      * holders followed `status`, a set of bit flags (1 byte each), i.e.
0574      * [val1*][holder1][val2*][holder2]...[bb...]  where each [block] is rounded up to a multiple of
0575      * `sizeof(void *)`.  `nonsimple.status` is, for convenience, a pointer to the
0576      * beginning of the [bb...] block (but not independently allocated).
0577      *
0578      * Status bits indicate whether the associated holder is constructed (&
0579      * status_holder_constructed) and whether the value pointer is registered (&
0580      * status_instance_registered) in `registered_instances`.
0581      */
0582     bool simple_layout : 1;
0583     /// For simple layout, tracks whether the holder has been constructed
0584     bool simple_holder_constructed : 1;
0585     /// For simple layout, tracks whether the instance is registered in `registered_instances`
0586     bool simple_instance_registered : 1;
0587     /// If true, get_internals().patients has an entry for this object
0588     bool has_patients : 1;
0589 
0590     /// Initializes all of the above type/values/holders data (but not the instance values themselves)
0591     void allocate_layout();
0592 
0593     /// Destroys/deallocates all of the above
0594     void deallocate_layout();
0595 
0596     /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
0597     /// omitted).  Returns a default-constructed (with `.inst = nullptr`) object on failure if
0598     /// `throw_if_missing` is false.
0599     value_and_holder get_value_and_holder(const type_info *find_type = nullptr, bool throw_if_missing = true);
0600 
0601     /// Bit values for the non-simple status flags
0602     static constexpr uint8_t status_holder_constructed  = 1;
0603     static constexpr uint8_t status_instance_registered = 2;
0604 };
0605 
0606 static_assert(std::is_standard_layout<instance>::value, "Internal error: `pybind11::detail::instance` is not standard layout!");
0607 
0608 /// from __cpp_future__ import (convenient aliases from C++14/17)
0609 #if defined(PYBIND11_CPP14) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
0610 using std::enable_if_t;
0611 using std::conditional_t;
0612 using std::remove_cv_t;
0613 using std::remove_reference_t;
0614 #else
0615 template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
0616 template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
0617 template <typename T> using remove_cv_t = typename std::remove_cv<T>::type;
0618 template <typename T> using remove_reference_t = typename std::remove_reference<T>::type;
0619 #endif
0620 
0621 #if defined(PYBIND11_CPP20)
0622 using std::remove_cvref;
0623 using std::remove_cvref_t;
0624 #else
0625 template <class T>
0626 struct remove_cvref {
0627     using type = remove_cv_t<remove_reference_t<T>>;
0628 };
0629 template <class T>
0630 using remove_cvref_t = typename remove_cvref<T>::type;
0631 #endif
0632 
0633 /// Index sequences
0634 #if defined(PYBIND11_CPP14)
0635 using std::index_sequence;
0636 using std::make_index_sequence;
0637 #else
0638 template<size_t ...> struct index_sequence  { };
0639 template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
0640 template<size_t ...S> struct make_index_sequence_impl <0, S...> { using type = index_sequence<S...>; };
0641 template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
0642 #endif
0643 
0644 /// Make an index sequence of the indices of true arguments
0645 template <typename ISeq, size_t, bool...> struct select_indices_impl { using type = ISeq; };
0646 template <size_t... IPrev, size_t I, bool B, bool... Bs> struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
0647     : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>, I + 1, Bs...> {};
0648 template <bool... Bs> using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
0649 
0650 /// Backports of std::bool_constant and std::negation to accommodate older compilers
0651 template <bool B> using bool_constant = std::integral_constant<bool, B>;
0652 template <typename T> struct negation : bool_constant<!T::value> { };
0653 
0654 // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
0655 // using the new one (C++14 defect, so generally works on newer compilers, even
0656 // if not in C++17 mode)
0657 #if defined(__PGIC__) || defined(__INTEL_COMPILER)
0658 template<typename... > using void_t = void;
0659 #else
0660 template <typename...> struct void_t_impl { using type = void; };
0661 template <typename... Ts> using void_t = typename void_t_impl<Ts...>::type;
0662 #endif
0663 
0664 
0665 /// Compile-time all/any/none of that check the boolean value of all template types
0666 #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
0667 template <class... Ts> using all_of = bool_constant<(Ts::value && ...)>;
0668 template <class... Ts> using any_of = bool_constant<(Ts::value || ...)>;
0669 #elif !defined(_MSC_VER)
0670 template <bool...> struct bools {};
0671 template <class... Ts> using all_of = std::is_same<
0672     bools<Ts::value..., true>,
0673     bools<true, Ts::value...>>;
0674 template <class... Ts> using any_of = negation<all_of<negation<Ts>...>>;
0675 #else
0676 // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
0677 // at a slight loss of compilation efficiency).
0678 template <class... Ts> using all_of = std::conjunction<Ts...>;
0679 template <class... Ts> using any_of = std::disjunction<Ts...>;
0680 #endif
0681 template <class... Ts> using none_of = negation<any_of<Ts...>>;
0682 
0683 template <class T, template<class> class... Predicates> using satisfies_all_of = all_of<Predicates<T>...>;
0684 template <class T, template<class> class... Predicates> using satisfies_any_of = any_of<Predicates<T>...>;
0685 template <class T, template<class> class... Predicates> using satisfies_none_of = none_of<Predicates<T>...>;
0686 
0687 /// Strip the class from a method type
0688 template <typename T> struct remove_class { };
0689 template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { using type = R (A...); };
0690 template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { using type = R (A...); };
0691 
0692 /// Helper template to strip away type modifiers
0693 template <typename T> struct intrinsic_type                       { using type = T; };
0694 template <typename T> struct intrinsic_type<const T>              { using type = typename intrinsic_type<T>::type; };
0695 template <typename T> struct intrinsic_type<T*>                   { using type = typename intrinsic_type<T>::type; };
0696 template <typename T> struct intrinsic_type<T&>                   { using type = typename intrinsic_type<T>::type; };
0697 template <typename T> struct intrinsic_type<T&&>                  { using type = typename intrinsic_type<T>::type; };
0698 template <typename T, size_t N> struct intrinsic_type<const T[N]> { using type = typename intrinsic_type<T>::type; };
0699 template <typename T, size_t N> struct intrinsic_type<T[N]>       { using type = typename intrinsic_type<T>::type; };
0700 template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
0701 
0702 /// Helper type to replace 'void' in some expressions
0703 struct void_type { };
0704 
0705 /// Helper template which holds a list of types
0706 template <typename...> struct type_list { };
0707 
0708 /// Compile-time integer sum
0709 #ifdef __cpp_fold_expressions
0710 template <typename... Ts> constexpr size_t constexpr_sum(Ts... ns) { return (0 + ... + size_t{ns}); }
0711 #else
0712 constexpr size_t constexpr_sum() { return 0; }
0713 template <typename T, typename... Ts>
0714 constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
0715 #endif
0716 
0717 PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
0718 /// Implementation details for constexpr functions
0719 constexpr int first(int i) { return i; }
0720 template <typename T, typename... Ts>
0721 constexpr int first(int i, T v, Ts... vs) { return v ? i : first(i + 1, vs...); }
0722 
0723 constexpr int last(int /*i*/, int result) { return result; }
0724 template <typename T, typename... Ts>
0725 constexpr int last(int i, int result, T v, Ts... vs) { return last(i + 1, v ? i : result, vs...); }
0726 PYBIND11_NAMESPACE_END(constexpr_impl)
0727 
0728 /// Return the index of the first type in Ts which satisfies Predicate<T>.  Returns sizeof...(Ts) if
0729 /// none match.
0730 template <template<typename> class Predicate, typename... Ts>
0731 constexpr int constexpr_first() { return constexpr_impl::first(0, Predicate<Ts>::value...); }
0732 
0733 /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
0734 template <template<typename> class Predicate, typename... Ts>
0735 constexpr int constexpr_last() { return constexpr_impl::last(0, -1, Predicate<Ts>::value...); }
0736 
0737 /// Return the Nth element from the parameter pack
0738 template <size_t N, typename T, typename... Ts>
0739 struct pack_element { using type = typename pack_element<N - 1, Ts...>::type; };
0740 template <typename T, typename... Ts>
0741 struct pack_element<0, T, Ts...> { using type = T; };
0742 
0743 /// Return the one and only type which matches the predicate, or Default if none match.
0744 /// If more than one type matches the predicate, fail at compile-time.
0745 template <template<typename> class Predicate, typename Default, typename... Ts>
0746 struct exactly_one {
0747     static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
0748     static_assert(found <= 1, "Found more than one type matching the predicate");
0749 
0750     static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
0751     using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
0752 };
0753 template <template<typename> class P, typename Default>
0754 struct exactly_one<P, Default> { using type = Default; };
0755 
0756 template <template<typename> class Predicate, typename Default, typename... Ts>
0757 using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
0758 
0759 /// Defer the evaluation of type T until types Us are instantiated
0760 template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
0761 template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
0762 
0763 /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
0764 /// unlike `std::is_base_of`)
0765 template <typename Base, typename Derived> using is_strict_base_of = bool_constant<
0766     std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
0767 
0768 /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived pointer
0769 /// can be converted to a Base pointer)
0770 /// For unions, `is_base_of<T, T>::value` is False, so we need to check `is_same` as well.
0771 template <typename Base, typename Derived> using is_accessible_base_of = bool_constant<
0772     (std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value) && std::is_convertible<Derived *, Base *>::value>;
0773 
0774 template <template<typename...> class Base>
0775 struct is_template_base_of_impl {
0776     template <typename... Us> static std::true_type check(Base<Us...> *);
0777     static std::false_type check(...);
0778 };
0779 
0780 /// Check if a template is the base of a type. For example:
0781 /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
0782 template <template<typename...> class Base, typename T>
0783 #if !defined(_MSC_VER)
0784 using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr));
0785 #else // MSVC2015 has trouble with decltype in template aliases
0786 struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };
0787 #endif
0788 
0789 /// Check if T is an instantiation of the template `Class`. For example:
0790 /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
0791 template <template<typename...> class Class, typename T>
0792 struct is_instantiation : std::false_type { };
0793 template <template<typename...> class Class, typename... Us>
0794 struct is_instantiation<Class, Class<Us...>> : std::true_type { };
0795 
0796 /// Check if T is std::shared_ptr<U> where U can be anything
0797 template <typename T> using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
0798 
0799 /// Check if T looks like an input iterator
0800 template <typename T, typename = void> struct is_input_iterator : std::false_type {};
0801 template <typename T>
0802 struct is_input_iterator<T, void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
0803     : std::true_type {};
0804 
0805 template <typename T> using is_function_pointer = bool_constant<
0806     std::is_pointer<T>::value && std::is_function<typename std::remove_pointer<T>::type>::value>;
0807 
0808 template <typename F> struct strip_function_object {
0809     // If you are encountering an
0810     // 'error: name followed by "::" must be a class or namespace name'
0811     // with the Intel compiler and a noexcept function here,
0812     // try to use noexcept(true) instead of plain noexcept.
0813     using type = typename remove_class<decltype(&F::operator())>::type;
0814 };
0815 
0816 // Extracts the function signature from a function, function pointer or lambda.
0817 template <typename Function, typename F = remove_reference_t<Function>>
0818 using function_signature_t = conditional_t<
0819     std::is_function<F>::value,
0820     F,
0821     typename conditional_t<
0822         std::is_pointer<F>::value || std::is_member_pointer<F>::value,
0823         std::remove_pointer<F>,
0824         strip_function_object<F>
0825     >::type
0826 >;
0827 
0828 /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
0829 /// pointer.  Note that this can catch all sorts of other things, too; this is intended to be used
0830 /// in a place where passing a lambda makes sense.
0831 template <typename T> using is_lambda = satisfies_none_of<remove_reference_t<T>,
0832         std::is_function, std::is_pointer, std::is_member_pointer>;
0833 
0834 // [workaround(intel)] Internal error on fold expression
0835 /// Apply a function over each element of a parameter pack
0836 #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
0837 // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
0838 #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
0839 #else
0840 using expand_side_effects = bool[];
0841 #define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (void)pybind11::detail::expand_side_effects{ ((PATTERN), void(), false)..., false }
0842 #endif
0843 
0844 PYBIND11_NAMESPACE_END(detail)
0845 
0846 #if defined(_MSC_VER)
0847 #  pragma warning(push)
0848 #  pragma warning(disable: 4275) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class.
0849 #endif
0850 /// C++ bindings of builtin Python exceptions
0851 class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
0852 public:
0853     using std::runtime_error::runtime_error;
0854     /// Set the error using the Python C API
0855     virtual void set_error() const = 0;
0856 };
0857 #if defined(_MSC_VER)
0858 #  pragma warning(pop)
0859 #endif
0860 
0861 #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
0862     class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { public: \
0863         using builtin_exception::builtin_exception; \
0864         name() : name("") { } \
0865         void set_error() const override { PyErr_SetString(type, what()); } \
0866     };
0867 
0868 PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
0869 PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
0870 PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
0871 PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
0872 PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
0873 PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
0874 PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
0875 PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
0876 PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
0877 PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
0878 
0879 [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
0880 [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
0881 
0882 template <typename T, typename SFINAE = void> struct format_descriptor { };
0883 
0884 PYBIND11_NAMESPACE_BEGIN(detail)
0885 // Returns the index of the given type in the type char array below, and in the list in numpy.h
0886 // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
0887 // complex float,double,long double.  Note that the long double types only participate when long
0888 // double is actually longer than double (it isn't under MSVC).
0889 // NB: not only the string below but also complex.h and numpy.h rely on this order.
0890 template <typename T, typename SFINAE = void> struct is_fmt_numeric { static constexpr bool value = false; };
0891 template <typename T> struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
0892     static constexpr bool value = true;
0893     static constexpr int index = std::is_same<T, bool>::value ? 0 : 1 + (
0894         std::is_integral<T>::value ? detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value : 8 + (
0895         std::is_same<T, double>::value ? 1 : std::is_same<T, long double>::value ? 2 : 0));
0896 };
0897 PYBIND11_NAMESPACE_END(detail)
0898 
0899 template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
0900     static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
0901     static constexpr const char value[2] = { c, '\0' };
0902     static std::string format() { return std::string(1, c); }
0903 };
0904 
0905 #if !defined(PYBIND11_CPP17)
0906 
0907 template <typename T> constexpr const char format_descriptor<
0908     T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
0909 
0910 #endif
0911 
0912 /// RAII wrapper that temporarily clears any Python error state
0913 struct error_scope {
0914     PyObject *type, *value, *trace;
0915     error_scope() { PyErr_Fetch(&type, &value, &trace); }
0916     ~error_scope() { PyErr_Restore(type, value, trace); }
0917 };
0918 
0919 /// Dummy destructor wrapper that can be used to expose classes with a private destructor
0920 struct nodelete { template <typename T> void operator()(T*) { } };
0921 
0922 PYBIND11_NAMESPACE_BEGIN(detail)
0923 template <typename... Args>
0924 struct overload_cast_impl {
0925     // NOLINTNEXTLINE(modernize-use-equals-default):  MSVC 2015 needs this
0926     constexpr overload_cast_impl() {}
0927 
0928     template <typename Return>
0929     constexpr auto operator()(Return (*pf)(Args...)) const noexcept
0930                               -> decltype(pf) { return pf; }
0931 
0932     template <typename Return, typename Class>
0933     constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
0934                               -> decltype(pmf) { return pmf; }
0935 
0936     template <typename Return, typename Class>
0937     constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
0938                               -> decltype(pmf) { return pmf; }
0939 };
0940 PYBIND11_NAMESPACE_END(detail)
0941 
0942 // overload_cast requires variable templates: C++14
0943 #if defined(PYBIND11_CPP14)
0944 #define PYBIND11_OVERLOAD_CAST 1
0945 /// Syntax sugar for resolving overloaded function pointers:
0946 ///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
0947 ///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
0948 template <typename... Args>
0949 static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
0950 // MSVC 2015 only accepts this particular initialization syntax for this variable template.
0951 #endif
0952 
0953 /// Const member function selector for overload_cast
0954 ///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
0955 ///  - sweet:   overload_cast<Arg>(&Class::func, const_)
0956 static constexpr auto const_ = std::true_type{};
0957 
0958 #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
0959 template <typename... Args> struct overload_cast {
0960     static_assert(detail::deferred_t<std::false_type, Args...>::value,
0961                   "pybind11::overload_cast<...> requires compiling in C++14 mode");
0962 };
0963 #endif // overload_cast
0964 
0965 PYBIND11_NAMESPACE_BEGIN(detail)
0966 
0967 // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
0968 // any standard container (or C-style array) supporting std::begin/std::end, any singleton
0969 // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
0970 template <typename T>
0971 class any_container {
0972     std::vector<T> v;
0973 public:
0974     any_container() = default;
0975 
0976     // Can construct from a pair of iterators
0977     template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
0978     any_container(It first, It last) : v(first, last) { }
0979 
0980     // Implicit conversion constructor from any arbitrary container type with values convertible to T
0981     template <typename Container, typename = enable_if_t<std::is_convertible<decltype(*std::begin(std::declval<const Container &>())), T>::value>>
0982     // NOLINTNEXTLINE(google-explicit-constructor)
0983     any_container(const Container &c) : any_container(std::begin(c), std::end(c)) { }
0984 
0985     // initializer_list's aren't deducible, so don't get matched by the above template; we need this
0986     // to explicitly allow implicit conversion from one:
0987     template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
0988     any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) { }
0989 
0990     // Avoid copying if given an rvalue vector of the correct type.
0991     // NOLINTNEXTLINE(google-explicit-constructor)
0992     any_container(std::vector<T> &&v) : v(std::move(v)) { }
0993 
0994     // Moves the vector out of an rvalue any_container
0995     // NOLINTNEXTLINE(google-explicit-constructor)
0996     operator std::vector<T> &&() && { return std::move(v); }
0997 
0998     // Dereferencing obtains a reference to the underlying vector
0999     std::vector<T> &operator*() { return v; }
1000     const std::vector<T> &operator*() const { return v; }
1001 
1002     // -> lets you call methods on the underlying vector
1003     std::vector<T> *operator->() { return &v; }
1004     const std::vector<T> *operator->() const { return &v; }
1005 };
1006 
1007 // Forward-declaration; see detail/class.h
1008 std::string get_fully_qualified_tp_name(PyTypeObject*);
1009 
1010 template <typename T>
1011 inline static std::shared_ptr<T> try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
1012 // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
1013 // Use at your own risk!
1014 // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
1015 // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
1016 #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1017     return holder_value_ptr->weak_from_this().lock();
1018 #else
1019     try {
1020         return holder_value_ptr->shared_from_this();
1021     }
1022     catch (const std::bad_weak_ptr &) {
1023         return nullptr;
1024     }
1025 #endif
1026 }
1027 
1028 // For silencing "unused" compiler warnings in special situations.
1029 template <typename... Args>
1030 #if defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER < 1920 // MSVC 2017
1031 constexpr
1032 #endif
1033 inline void silence_unused_warnings(Args &&...) {}
1034 
1035 // MSVC warning C4100: Unreferenced formal parameter
1036 #if defined(_MSC_VER) && _MSC_VER <= 1916
1037 #    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)                                         \
1038         detail::silence_unused_warnings(__VA_ARGS__)
1039 #else
1040 #    define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
1041 #endif
1042 
1043 // GCC -Wunused-but-set-parameter  All GCC versions (as of July 2021).
1044 #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
1045 #    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)                   \
1046         detail::silence_unused_warnings(__VA_ARGS__)
1047 #else
1048 #    define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
1049 #endif
1050 
1051 #if defined(_MSC_VER) // All versions (as of July 2021).
1052 
1053 // warning C4127: Conditional expression is constant
1054 constexpr inline bool silence_msvc_c4127(bool cond) { return cond; }
1055 
1056 #    define PYBIND11_SILENCE_MSVC_C4127(...) ::pybind11::detail::silence_msvc_c4127(__VA_ARGS__)
1057 
1058 #else
1059 #    define PYBIND11_SILENCE_MSVC_C4127(...) __VA_ARGS__
1060 #endif
1061 
1062 PYBIND11_NAMESPACE_END(detail)
1063 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)