common.h revision 11986:c12e4625ab56
1/*
2    pybind11/common.h -- Basic macros
3
4    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6    All rights reserved. Use of this source code is governed by a
7    BSD-style license that can be found in the LICENSE file.
8*/
9
10#pragma once
11
12#if !defined(NAMESPACE_BEGIN)
13#  define NAMESPACE_BEGIN(name) namespace name {
14#endif
15#if !defined(NAMESPACE_END)
16#  define NAMESPACE_END(name) }
17#endif
18
19// Neither MSVC nor Intel support enough of C++14 yet (in particular, as of MSVC 2015 and ICC 17
20// beta, neither support extended constexpr, which we rely on in descr.h), so don't enable pybind
21// CPP14 features for them.
22#if !defined(_MSC_VER) && !defined(__INTEL_COMPILER)
23#  if __cplusplus >= 201402L
24#    define PYBIND11_CPP14
25#    if __cplusplus > 201402L /* Temporary: should be updated to >= the final C++17 value once known */
26#      define PYBIND11_CPP17
27#    endif
28#  endif
29#endif
30
31#if !defined(PYBIND11_EXPORT)
32#  if defined(WIN32) || defined(_WIN32)
33#    define PYBIND11_EXPORT __declspec(dllexport)
34#  else
35#    define PYBIND11_EXPORT __attribute__ ((visibility("default")))
36#  endif
37#endif
38
39#if defined(_MSC_VER)
40#  define PYBIND11_NOINLINE __declspec(noinline)
41#else
42#  define PYBIND11_NOINLINE __attribute__ ((noinline))
43#endif
44
45#if defined(PYBIND11_CPP14)
46#  define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
47#elif defined(__clang__)
48#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
49#elif defined(__GNUG__)
50#  define PYBIND11_DEPRECATED(reason) __attribute__((deprecated))
51#elif defined(_MSC_VER)
52#  define PYBIND11_DEPRECATED(reason) __declspec(deprecated)
53#endif
54
55#define PYBIND11_VERSION_MAJOR 1
56#define PYBIND11_VERSION_MINOR 9
57#define PYBIND11_VERSION_PATCH dev0
58
59/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
60#if defined(_MSC_VER)
61#  define HAVE_ROUND
62#  pragma warning(push)
63#  pragma warning(disable: 4510 4610 4512 4005)
64#  if _DEBUG
65#    define PYBIND11_DEBUG_MARKER
66#    undef _DEBUG
67#  endif
68#endif
69
70#include <Python.h>
71#include <frameobject.h>
72#include <pythread.h>
73
74#if defined(_WIN32) && (defined(min) || defined(max))
75#  error Macro clash with min and max -- define NOMINMAX when compiling your program on Windows
76#endif
77
78#if defined(isalnum)
79#  undef isalnum
80#  undef isalpha
81#  undef islower
82#  undef isspace
83#  undef isupper
84#  undef tolower
85#  undef toupper
86#endif
87
88#if defined(_MSC_VER)
89#  if defined(PYBIND11_DEBUG_MARKER)
90#    define _DEBUG
91#    undef PYBIND11_DEBUG_MARKER
92#  endif
93#  pragma warning(pop)
94#endif
95
96#include <cstddef>
97#include <forward_list>
98#include <vector>
99#include <string>
100#include <stdexcept>
101#include <unordered_set>
102#include <unordered_map>
103#include <memory>
104#include <typeindex>
105#include <type_traits>
106
107#if PY_MAJOR_VERSION >= 3 /// Compatibility macros for various Python versions
108#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
109#define PYBIND11_BYTES_CHECK PyBytes_Check
110#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
111#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
112#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
113#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
114#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
115#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
116#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) PyLong_AsUnsignedLongLong(o)
117#define PYBIND11_BYTES_NAME "bytes"
118#define PYBIND11_STRING_NAME "str"
119#define PYBIND11_SLICE_OBJECT PyObject
120#define PYBIND11_FROM_STRING PyUnicode_FromString
121#define PYBIND11_STR_TYPE ::pybind11::str
122#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_base.ob_base.ob_type
123#define PYBIND11_PLUGIN_IMPL(name) \
124    extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
125#else
126#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
127#define PYBIND11_BYTES_CHECK PyString_Check
128#define PYBIND11_BYTES_FROM_STRING PyString_FromString
129#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyString_FromStringAndSize
130#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyString_AsStringAndSize
131#define PYBIND11_BYTES_AS_STRING PyString_AsString
132#define PYBIND11_LONG_CHECK(o) (PyInt_Check(o) || PyLong_Check(o))
133#define PYBIND11_LONG_AS_LONGLONG(o) (PyInt_Check(o) ? (long long) PyLong_AsLong(o) : PyLong_AsLongLong(o))
134#define PYBIND11_LONG_AS_UNSIGNED_LONGLONG(o) (PyInt_Check(o) ? (unsigned long long) PyLong_AsUnsignedLong(o) : PyLong_AsUnsignedLongLong(o))
135#define PYBIND11_BYTES_NAME "str"
136#define PYBIND11_STRING_NAME "unicode"
137#define PYBIND11_SLICE_OBJECT PySliceObject
138#define PYBIND11_FROM_STRING PyString_FromString
139#define PYBIND11_STR_TYPE ::pybind11::bytes
140#define PYBIND11_OB_TYPE(ht_type) (ht_type).ob_type
141#define PYBIND11_PLUGIN_IMPL(name) \
142    extern "C" PYBIND11_EXPORT PyObject *init##name()
143#endif
144
145#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
146extern "C" {
147    struct _Py_atomic_address { void *value; };
148    PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
149}
150#endif
151
152#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
153#define PYBIND11_STRINGIFY(x) #x
154#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
155#define PYBIND11_INTERNALS_ID "__pybind11_" \
156    PYBIND11_TOSTRING(PYBIND11_VERSION_MAJOR) "_" PYBIND11_TOSTRING(PYBIND11_VERSION_MINOR) "__"
157
158#define PYBIND11_PLUGIN(name)                                                  \
159    static PyObject *pybind11_init();                                          \
160    PYBIND11_PLUGIN_IMPL(name) {                                               \
161        int major, minor;                                                      \
162        if (sscanf(Py_GetVersion(), "%i.%i", &major, &minor) != 2) {           \
163            PyErr_SetString(PyExc_ImportError, "Can't parse Python version."); \
164            return nullptr;                                                    \
165        } else if (major != PY_MAJOR_VERSION || minor != PY_MINOR_VERSION) {   \
166            PyErr_Format(PyExc_ImportError,                                    \
167                         "Python version mismatch: module was compiled for "   \
168                         "version %i.%i, while the interpreter is running "    \
169                         "version %i.%i.", PY_MAJOR_VERSION, PY_MINOR_VERSION, \
170                         major, minor);                                        \
171            return nullptr;                                                    \
172        }                                                                      \
173        try {                                                                  \
174            return pybind11_init();                                            \
175        } catch (const std::exception &e) {                                    \
176            PyErr_SetString(PyExc_ImportError, e.what());                      \
177            return nullptr;                                                    \
178        }                                                                      \
179    }                                                                          \
180    PyObject *pybind11_init()
181
182NAMESPACE_BEGIN(pybind11)
183
184using ssize_t = Py_ssize_t;
185using size_t  = std::size_t;
186
187/// Approach used to cast a previously unknown C++ instance into a Python object
188enum class return_value_policy : uint8_t {
189    /** This is the default return value policy, which falls back to the policy
190        return_value_policy::take_ownership when the return value is a pointer.
191        Otherwise, it uses return_value::move or return_value::copy for rvalue
192        and lvalue references, respectively. See below for a description of what
193        all of these different policies do. */
194    automatic = 0,
195
196    /** As above, but use policy return_value_policy::reference when the return
197        value is a pointer. This is the default conversion policy for function
198        arguments when calling Python functions manually from C++ code (i.e. via
199        handle::operator()). You probably won't need to use this. */
200    automatic_reference,
201
202    /** Reference an existing object (i.e. do not create a new copy) and take
203        ownership. Python will call the destructor and delete operator when the
204        object’s reference count reaches zero. Undefined behavior ensues when
205        the C++ side does the same.. */
206    take_ownership,
207
208    /** Create a new copy of the returned object, which will be owned by
209        Python. This policy is comparably safe because the lifetimes of the two
210        instances are decoupled. */
211    copy,
212
213    /** Use std::move to move the return value contents into a new instance
214        that will be owned by Python. This policy is comparably safe because the
215        lifetimes of the two instances (move source and destination) are
216        decoupled. */
217    move,
218
219    /** Reference an existing object, but do not take ownership. The C++ side
220        is responsible for managing the object’s lifetime and deallocating it
221        when it is no longer used. Warning: undefined behavior will ensue when
222        the C++ side deletes an object that is still referenced and used by
223        Python. */
224    reference,
225
226    /** This policy only applies to methods and properties. It references the
227        object without taking ownership similar to the above
228        return_value_policy::reference policy. In contrast to that policy, the
229        function or property’s implicit this argument (called the parent) is
230        considered to be the the owner of the return value (the child).
231        pybind11 then couples the lifetime of the parent to the child via a
232        reference relationship that ensures that the parent cannot be garbage
233        collected while Python is still using the child. More advanced
234        variations of this scheme are also possible using combinations of
235        return_value_policy::reference and the keep_alive call policy */
236    reference_internal
237};
238
239/// Information record describing a Python buffer object
240struct buffer_info {
241    void *ptr = nullptr;         // Pointer to the underlying storage
242    size_t itemsize = 0;         // Size of individual items in bytes
243    size_t size = 0;             // Total number of entries
244    std::string format;          // For homogeneous buffers, this should be set to format_descriptor<T>::format()
245    size_t ndim = 0;             // Number of dimensions
246    std::vector<size_t> shape;   // Shape of the tensor (1 entry per dimension)
247    std::vector<size_t> strides; // Number of entries between adjacent entries (for each per dimension)
248
249    buffer_info() { }
250
251    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t ndim,
252                const std::vector<size_t> &shape, const std::vector<size_t> &strides)
253        : ptr(ptr), itemsize(itemsize), size(1), format(format),
254          ndim(ndim), shape(shape), strides(strides) {
255        for (size_t i = 0; i < ndim; ++i)
256            size *= shape[i];
257    }
258
259    buffer_info(void *ptr, size_t itemsize, const std::string &format, size_t size)
260    : buffer_info(ptr, itemsize, format, 1, std::vector<size_t> { size },
261                  std::vector<size_t> { itemsize }) { }
262
263    explicit buffer_info(Py_buffer *view, bool ownview = true)
264        : ptr(view->buf), itemsize((size_t) view->itemsize), size(1), format(view->format),
265          ndim((size_t) view->ndim), shape((size_t) view->ndim), strides((size_t) view->ndim), view(view), ownview(ownview) {
266        for (size_t i = 0; i < (size_t) view->ndim; ++i) {
267            shape[i] = (size_t) view->shape[i];
268            strides[i] = (size_t) view->strides[i];
269            size *= shape[i];
270        }
271    }
272
273    buffer_info(const buffer_info &) = delete;
274    buffer_info& operator=(const buffer_info &) = delete;
275
276    buffer_info(buffer_info &&other) {
277        (*this) = std::move(other);
278    }
279
280    buffer_info& operator=(buffer_info &&rhs) {
281        ptr = rhs.ptr;
282        itemsize = rhs.itemsize;
283        size = rhs.size;
284        format = std::move(rhs.format);
285        ndim = rhs.ndim;
286        shape = std::move(rhs.shape);
287        strides = std::move(rhs.strides);
288        std::swap(view, rhs.view);
289        std::swap(ownview, rhs.ownview);
290        return *this;
291    }
292
293    ~buffer_info() {
294        if (view && ownview) { PyBuffer_Release(view); delete view; }
295    }
296
297private:
298    Py_buffer *view = nullptr;
299    bool ownview = false;
300};
301
302NAMESPACE_BEGIN(detail)
303
304inline static constexpr int log2(size_t n, int k = 0) { return (n <= 1) ? k : log2(n >> 1, k + 1); }
305
306inline std::string error_string();
307
308/// Core part of the 'instance' type which POD (needed to be able to use 'offsetof')
309template <typename type> struct instance_essentials {
310    PyObject_HEAD
311    type *value;
312    PyObject *weakrefs;
313    bool owned : 1;
314    bool holder_constructed : 1;
315};
316
317/// PyObject wrapper around generic types, includes a special holder type that is responsible for lifetime management
318template <typename type, typename holder_type = std::unique_ptr<type>> struct instance : instance_essentials<type> {
319    holder_type holder;
320};
321
322struct overload_hash {
323    inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const {
324        size_t value = std::hash<const void *>()(v.first);
325        value ^= std::hash<const void *>()(v.second)  + 0x9e3779b9 + (value<<6) + (value>>2);
326        return value;
327    }
328};
329
330/// Internal data struture used to track registered instances and types
331struct internals {
332    std::unordered_map<std::type_index, void*> registered_types_cpp;   // std::type_index -> type_info
333    std::unordered_map<const void *, void*> registered_types_py;       // PyTypeObject* -> type_info
334    std::unordered_multimap<const void *, void*> registered_instances; // void * -> PyObject*
335    std::unordered_set<std::pair<const PyObject *, const char *>, overload_hash> inactive_overload_cache;
336    std::unordered_map<std::type_index, std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
337    std::forward_list<void (*) (std::exception_ptr)> registered_exception_translators;
338    std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions
339#if defined(WITH_THREAD)
340    decltype(PyThread_create_key()) tstate = 0; // Usually an int but a long on Cygwin64 with Python 3.x
341    PyInterpreterState *istate = nullptr;
342#endif
343};
344
345/// Return a reference to the current 'internals' information
346inline internals &get_internals();
347
348/// Index sequence for convenient template metaprogramming involving tuples
349#ifdef PYBIND11_CPP14
350using std::index_sequence;
351using std::make_index_sequence;
352#else
353template<size_t ...> struct index_sequence  { };
354template<size_t N, size_t ...S> struct make_index_sequence_impl : make_index_sequence_impl <N - 1, N - 1, S...> { };
355template<size_t ...S> struct make_index_sequence_impl <0, S...> { typedef index_sequence<S...> type; };
356template<size_t N> using make_index_sequence = typename make_index_sequence_impl<N>::type;
357#endif
358
359/// Strip the class from a method type
360template <typename T> struct remove_class { };
361template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...)> { typedef R type(A...); };
362template <typename C, typename R, typename... A> struct remove_class<R (C::*)(A...) const> { typedef R type(A...); };
363
364/// Helper template to strip away type modifiers
365template <typename T> struct intrinsic_type                       { typedef T type; };
366template <typename T> struct intrinsic_type<const T>              { typedef typename intrinsic_type<T>::type type; };
367template <typename T> struct intrinsic_type<T*>                   { typedef typename intrinsic_type<T>::type type; };
368template <typename T> struct intrinsic_type<T&>                   { typedef typename intrinsic_type<T>::type type; };
369template <typename T> struct intrinsic_type<T&&>                  { typedef typename intrinsic_type<T>::type type; };
370template <typename T, size_t N> struct intrinsic_type<const T[N]> { typedef typename intrinsic_type<T>::type type; };
371template <typename T, size_t N> struct intrinsic_type<T[N]>       { typedef typename intrinsic_type<T>::type type; };
372template <typename T> using intrinsic_t = typename intrinsic_type<T>::type;
373
374/// Helper type to replace 'void' in some expressions
375struct void_type { };
376
377/// Helper template which holds a list of types
378template <typename...> struct type_list { };
379
380/// from __cpp_future__ import (convenient aliases from C++14/17)
381template <bool B> using bool_constant = std::integral_constant<bool, B>;
382template <class T> using negation = bool_constant<!T::value>;
383template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type;
384template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type;
385
386/// Compile-time integer sum
387constexpr size_t constexpr_sum() { return 0; }
388template <typename T, typename... Ts>
389constexpr size_t constexpr_sum(T n, Ts... ns) { return size_t{n} + constexpr_sum(ns...); }
390
391// Counts the number of types in the template parameter pack matching the predicate
392#if !defined(_MSC_VER)
393template <template<typename> class Predicate, typename... Ts>
394using count_t = std::integral_constant<size_t, constexpr_sum(Predicate<Ts>::value...)>;
395#else
396// MSVC workaround (2015 Update 3 has issues with some member type aliases and constexpr)
397template <template<typename> class Predicate, typename... Ts> struct count_t;
398template <template<typename> class Predicate> struct count_t<Predicate> : std::integral_constant<size_t, 0> {};
399template <template<typename> class Predicate, class T, class... Ts>
400struct count_t<Predicate, T, Ts...> : std::integral_constant<size_t, Predicate<T>::value + count_t<Predicate, Ts...>::value> {};
401#endif
402
403/// Return true if all/any Ts satify Predicate<T>
404template <template<typename> class Predicate, typename... Ts>
405using all_of_t = bool_constant<(count_t<Predicate, Ts...>::value == sizeof...(Ts))>;
406template <template<typename> class Predicate, typename... Ts>
407using any_of_t = bool_constant<(count_t<Predicate, Ts...>::value > 0)>;
408
409// Extracts the first type from the template parameter pack matching the predicate, or Default if none match.
410template <template<class> class Predicate, class Default, class... Ts> struct first_of;
411template <template<class> class Predicate, class Default> struct first_of<Predicate, Default> {
412    using type = Default;
413};
414template <template<class> class Predicate, class Default, class T, class... Ts>
415struct first_of<Predicate, Default, T, Ts...> {
416    using type = typename std::conditional<
417        Predicate<T>::value,
418        T,
419        typename first_of<Predicate, Default, Ts...>::type
420    >::type;
421};
422template <template<class> class Predicate, class Default, class... T> using first_of_t = typename first_of<Predicate, Default, T...>::type;
423
424/// Defer the evaluation of type T until types Us are instantiated
425template <typename T, typename... /*Us*/> struct deferred_type { using type = T; };
426template <typename T, typename... Us> using deferred_t = typename deferred_type<T, Us...>::type;
427
428template <template<typename...> class Base>
429struct is_template_base_of_impl {
430    template <typename... Us> static std::true_type check(Base<Us...> *);
431    static std::false_type check(...);
432};
433
434/// Check if a template is the base of a type. For example:
435/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
436template <template<typename...> class Base, typename T>
437#if !defined(_MSC_VER)
438using is_template_base_of = decltype(is_template_base_of_impl<Base>::check((T*)nullptr));
439#else // MSVC2015 has trouble with decltype in template aliases
440struct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((T*)nullptr)) { };
441#endif
442
443/// Check if T is std::shared_ptr<U> where U can be anything
444template <typename T> struct is_shared_ptr : std::false_type { };
445template <typename U> struct is_shared_ptr<std::shared_ptr<U>> : std::true_type { };
446
447/// Ignore that a variable is unused in compiler warnings
448inline void ignore_unused(const int *) { }
449
450NAMESPACE_END(detail)
451
452/// Returns a named pointer that is shared among all extension modules (using the same
453/// pybind11 version) running in the current interpreter. Names starting with underscores
454/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
455inline PYBIND11_NOINLINE void* get_shared_data(const std::string& name) {
456    auto& internals = detail::get_internals();
457    auto it = internals.shared_data.find(name);
458    return it != internals.shared_data.end() ? it->second : nullptr;
459}
460
461/// Set the shared data that can be later recovered by `get_shared_data()`.
462inline PYBIND11_NOINLINE void *set_shared_data(const std::string& name, void *data) {
463    detail::get_internals().shared_data[name] = data;
464    return data;
465}
466
467/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
468/// such entry exists. Otherwise, a new object of default-constructible type `T` is
469/// added to the shared data under the given name and a reference to it is returned.
470template<typename T> T& get_or_create_shared_data(const std::string& name) {
471    auto& internals = detail::get_internals();
472    auto it = internals.shared_data.find(name);
473    T* ptr = (T*) (it != internals.shared_data.end() ? it->second : nullptr);
474    if (!ptr) {
475        ptr = new T();
476        internals.shared_data[name] = ptr;
477    }
478    return *ptr;
479}
480
481/// Fetch and hold an error which was already set in Python
482class error_already_set : public std::runtime_error {
483public:
484    error_already_set() : std::runtime_error(detail::error_string()) {
485        PyErr_Fetch(&type, &value, &trace);
486    }
487
488    error_already_set(const error_already_set &) = delete;
489
490    error_already_set(error_already_set &&e)
491        : std::runtime_error(e.what()), type(e.type), value(e.value),
492          trace(e.trace) { e.type = e.value = e.trace = nullptr; }
493
494    inline ~error_already_set(); // implementation in pybind11.h
495
496    error_already_set& operator=(const error_already_set &) = delete;
497
498    /// Give the error back to Python
499    void restore() { PyErr_Restore(type, value, trace); type = value = trace = nullptr; }
500
501private:
502    PyObject *type, *value, *trace;
503};
504
505/// C++ bindings of builtin Python exceptions
506class builtin_exception : public std::runtime_error {
507public:
508    using std::runtime_error::runtime_error;
509    virtual void set_error() const = 0; /// Set the error using the Python C API
510};
511
512#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
513    class name : public builtin_exception { public: \
514        using builtin_exception::builtin_exception; \
515        name() : name("") { } \
516        void set_error() const override { PyErr_SetString(type, what()); } \
517    };
518
519PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
520PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
521PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
522PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
523PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
524PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or handle::call fail due to a type casting error
525PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
526
527[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const char *reason) { throw std::runtime_error(reason); }
528[[noreturn]] PYBIND11_NOINLINE inline void pybind11_fail(const std::string &reason) { throw std::runtime_error(reason); }
529
530/// Format strings for basic number types
531#define PYBIND11_DECL_FMT(t, v) template<> struct format_descriptor<t> \
532    { static constexpr const char* value = v; /* for backwards compatibility */ \
533      static std::string format() { return value; } }
534
535template <typename T, typename SFINAE = void> struct format_descriptor { };
536
537template <typename T> struct format_descriptor<T, detail::enable_if_t<std::is_integral<T>::value>> {
538    static constexpr const char c = "bBhHiIqQ"[detail::log2(sizeof(T))*2 + std::is_unsigned<T>::value];
539    static constexpr const char value[2] = { c, '\0' };
540    static std::string format() { return std::string(1, c); }
541};
542
543template <typename T> constexpr const char format_descriptor<
544    T, detail::enable_if_t<std::is_integral<T>::value>>::value[2];
545
546/// RAII wrapper that temporarily clears any Python error state
547struct error_scope {
548    PyObject *type, *value, *trace;
549    error_scope() { PyErr_Fetch(&type, &value, &trace); }
550    ~error_scope() { PyErr_Restore(type, value, trace); }
551};
552
553PYBIND11_DECL_FMT(float, "f");
554PYBIND11_DECL_FMT(double, "d");
555PYBIND11_DECL_FMT(bool, "?");
556
557/// Dummy destructor wrapper that can be used to expose classes with a private destructor
558struct nodelete { template <typename T> void operator()(T*) { } };
559
560// overload_cast requires variable templates: C++14 or MSVC 2015 Update 2
561#if defined(PYBIND11_CPP14) || _MSC_FULL_VER >= 190023918
562#define PYBIND11_OVERLOAD_CAST 1
563
564NAMESPACE_BEGIN(detail)
565template <typename... Args>
566struct overload_cast_impl {
567    template <typename Return>
568    constexpr auto operator()(Return (*pf)(Args...)) const noexcept
569                              -> decltype(pf) { return pf; }
570
571    template <typename Return, typename Class>
572    constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
573                              -> decltype(pmf) { return pmf; }
574
575    template <typename Return, typename Class>
576    constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
577                              -> decltype(pmf) { return pmf; }
578};
579NAMESPACE_END(detail)
580
581/// Syntax sugar for resolving overloaded function pointers:
582///  - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
583///  - sweet:   overload_cast<Arg0, Arg1, Arg2>(&Class::func)
584template <typename... Args>
585static constexpr detail::overload_cast_impl<Args...> overload_cast = {};
586// MSVC 2015 only accepts this particular initialization syntax for this variable template.
587
588/// Const member function selector for overload_cast
589///  - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
590///  - sweet:   overload_cast<Arg>(&Class::func, const_)
591static constexpr auto const_ = std::true_type{};
592
593#endif // overload_cast
594
595NAMESPACE_END(pybind11)
596