Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:17:52

0001 /*
0002     tests/test_class.cpp -- test py::class_ definitions and basic functionality
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 #if defined(__INTEL_COMPILER) && __cplusplus >= 201703L
0011 // Intel compiler requires a separate header file to support aligned new operators
0012 // and does not set the __cpp_aligned_new feature macro.
0013 // This header needs to be included before pybind11.
0014 #    include <aligned_new>
0015 #endif
0016 
0017 #include <pybind11/stl.h>
0018 
0019 #include "constructor_stats.h"
0020 #include "local_bindings.h"
0021 #include "pybind11_tests.h"
0022 
0023 #include <utility>
0024 
0025 PYBIND11_WARNING_DISABLE_MSVC(4324)
0026 //     warning C4324: structure was padded due to alignment specifier
0027 
0028 // test_brace_initialization
0029 struct NoBraceInitialization {
0030     explicit NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
0031     template <typename T>
0032     NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
0033 
0034     std::vector<int> vec;
0035 };
0036 
0037 namespace test_class {
0038 namespace pr4220_tripped_over_this { // PR #4227
0039 
0040 template <int>
0041 struct SoEmpty {};
0042 
0043 template <typename T>
0044 std::string get_msg(const T &) {
0045     return "This is really only meant to exercise successful compilation.";
0046 }
0047 
0048 using Empty0 = SoEmpty<0x0>;
0049 
0050 void bind_empty0(py::module_ &m) {
0051     py::class_<Empty0>(m, "Empty0").def(py::init<>()).def("get_msg", get_msg<Empty0>);
0052 }
0053 
0054 } // namespace pr4220_tripped_over_this
0055 } // namespace test_class
0056 
0057 TEST_SUBMODULE(class_, m) {
0058     m.def("obj_class_name", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });
0059 
0060     // test_instance
0061     struct NoConstructor {
0062         NoConstructor() = default;
0063         NoConstructor(const NoConstructor &) = default;
0064         NoConstructor(NoConstructor &&) = default;
0065         static NoConstructor *new_instance() {
0066             auto *ptr = new NoConstructor();
0067             print_created(ptr, "via new_instance");
0068             return ptr;
0069         }
0070         ~NoConstructor() { print_destroyed(this); }
0071     };
0072     struct NoConstructorNew {
0073         NoConstructorNew() = default;
0074         NoConstructorNew(const NoConstructorNew &) = default;
0075         NoConstructorNew(NoConstructorNew &&) = default;
0076         static NoConstructorNew *new_instance() {
0077             auto *ptr = new NoConstructorNew();
0078             print_created(ptr, "via new_instance");
0079             return ptr;
0080         }
0081         ~NoConstructorNew() { print_destroyed(this); }
0082     };
0083 
0084     py::class_<NoConstructor>(m, "NoConstructor")
0085         .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
0086 
0087     py::class_<NoConstructorNew>(m, "NoConstructorNew")
0088         .def(py::init([](const NoConstructorNew &self) { return self; })) // Need a NOOP __init__
0089         .def_static("__new__",
0090                     [](const py::object &) { return NoConstructorNew::new_instance(); });
0091 
0092     // test_inheritance
0093     class Pet {
0094     public:
0095         Pet(const std::string &name, const std::string &species)
0096             : m_name(name), m_species(species) {}
0097         std::string name() const { return m_name; }
0098         std::string species() const { return m_species; }
0099 
0100     private:
0101         std::string m_name;
0102         std::string m_species;
0103     };
0104 
0105     class Dog : public Pet {
0106     public:
0107         explicit Dog(const std::string &name) : Pet(name, "dog") {}
0108         std::string bark() const { return "Woof!"; }
0109     };
0110 
0111     class Rabbit : public Pet {
0112     public:
0113         explicit Rabbit(const std::string &name) : Pet(name, "parrot") {}
0114     };
0115 
0116     class Hamster : public Pet {
0117     public:
0118         explicit Hamster(const std::string &name) : Pet(name, "rodent") {}
0119     };
0120 
0121     class Chimera : public Pet {
0122         Chimera() : Pet("Kimmy", "chimera") {}
0123     };
0124 
0125     py::class_<Pet> pet_class(m, "Pet");
0126     pet_class.def(py::init<std::string, std::string>())
0127         .def("name", &Pet::name)
0128         .def("species", &Pet::species);
0129 
0130     /* One way of declaring a subclass relationship: reference parent's class_ object */
0131     py::class_<Dog>(m, "Dog", pet_class).def(py::init<std::string>());
0132 
0133     /* Another way of declaring a subclass relationship: reference parent's C++ type */
0134     py::class_<Rabbit, Pet>(m, "Rabbit").def(py::init<std::string>());
0135 
0136     /* And another: list parent in class template arguments */
0137     py::class_<Hamster, Pet>(m, "Hamster").def(py::init<std::string>());
0138 
0139     /* Constructors are not inherited by default */
0140     py::class_<Chimera, Pet>(m, "Chimera");
0141 
0142     m.def("pet_name_species",
0143           [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
0144     m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
0145 
0146     // test_automatic_upcasting
0147     struct BaseClass {
0148         BaseClass() = default;
0149         BaseClass(const BaseClass &) = default;
0150         BaseClass(BaseClass &&) = default;
0151         virtual ~BaseClass() = default;
0152     };
0153     struct DerivedClass1 : BaseClass {};
0154     struct DerivedClass2 : BaseClass {};
0155 
0156     py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
0157     py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
0158     py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
0159 
0160     m.def("return_class_1", []() -> BaseClass * { return new DerivedClass1(); });
0161     m.def("return_class_2", []() -> BaseClass * { return new DerivedClass2(); });
0162     m.def("return_class_n", [](int n) -> BaseClass * {
0163         if (n == 1) {
0164             return new DerivedClass1();
0165         }
0166         if (n == 2) {
0167             return new DerivedClass2();
0168         }
0169         return new BaseClass();
0170     });
0171     m.def("return_none", []() -> BaseClass * { return nullptr; });
0172 
0173     // test_isinstance
0174     m.def("check_instances", [](const py::list &l) {
0175         return py::make_tuple(py::isinstance<py::tuple>(l[0]),
0176                               py::isinstance<py::dict>(l[1]),
0177                               py::isinstance<Pet>(l[2]),
0178                               py::isinstance<Pet>(l[3]),
0179                               py::isinstance<Dog>(l[4]),
0180                               py::isinstance<Rabbit>(l[5]),
0181                               py::isinstance<UnregisteredType>(l[6]));
0182     });
0183 
0184     struct Invalid {};
0185 
0186     // test_type
0187     m.def("check_type", [](int category) {
0188         // Currently not supported (via a fail at compile time)
0189         // See https://github.com/pybind/pybind11/issues/2486
0190         // if (category == 2)
0191         //     return py::type::of<int>();
0192         if (category == 1) {
0193             return py::type::of<DerivedClass1>();
0194         }
0195         return py::type::of<Invalid>();
0196     });
0197 
0198     m.def("get_type_of", [](py::object ob) { return py::type::of(std::move(ob)); });
0199 
0200     m.def("get_type_classic", [](py::handle h) { return h.get_type(); });
0201 
0202     m.def("as_type", [](const py::object &ob) { return py::type(ob); });
0203 
0204     // test_mismatched_holder
0205     struct MismatchBase1 {};
0206     struct MismatchDerived1 : MismatchBase1 {};
0207 
0208     struct MismatchBase2 {};
0209     struct MismatchDerived2 : MismatchBase2 {};
0210 
0211     m.def("mismatched_holder_1", []() {
0212         auto mod = py::module_::import("__main__");
0213         py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
0214         py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
0215     });
0216     m.def("mismatched_holder_2", []() {
0217         auto mod = py::module_::import("__main__");
0218         py::class_<MismatchBase2>(mod, "MismatchBase2");
0219         py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>, MismatchBase2>(
0220             mod, "MismatchDerived2");
0221     });
0222 
0223     // test_override_static
0224     // #511: problem with inheritance + overwritten def_static
0225     struct MyBase {
0226         static std::unique_ptr<MyBase> make() { return std::unique_ptr<MyBase>(new MyBase()); }
0227     };
0228 
0229     struct MyDerived : MyBase {
0230         static std::unique_ptr<MyDerived> make() {
0231             return std::unique_ptr<MyDerived>(new MyDerived());
0232         }
0233     };
0234 
0235     py::class_<MyBase>(m, "MyBase").def_static("make", &MyBase::make);
0236 
0237     py::class_<MyDerived, MyBase>(m, "MyDerived")
0238         .def_static("make", &MyDerived::make)
0239         .def_static("make2", &MyDerived::make);
0240 
0241     // test_implicit_conversion_life_support
0242     struct ConvertibleFromUserType {
0243         int i;
0244 
0245         explicit ConvertibleFromUserType(UserType u) : i(u.value()) {}
0246     };
0247 
0248     py::class_<ConvertibleFromUserType>(m, "AcceptsUserType").def(py::init<UserType>());
0249     py::implicitly_convertible<UserType, ConvertibleFromUserType>();
0250 
0251     m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
0252     m.def("implicitly_convert_variable", [](const py::object &o) {
0253         // `o` is `UserType` and `r` is a reference to a temporary created by implicit
0254         // conversion. This is valid when called inside a bound function because the temp
0255         // object is attached to the same life support system as the arguments.
0256         const auto &r = o.cast<const ConvertibleFromUserType &>();
0257         return r.i;
0258     });
0259     m.add_object("implicitly_convert_variable_fail", [&] {
0260         auto f = [](PyObject *, PyObject *args) -> PyObject * {
0261             auto o = py::reinterpret_borrow<py::tuple>(args)[0];
0262             try { // It should fail here because there is no life support.
0263                 o.cast<const ConvertibleFromUserType &>();
0264             } catch (const py::cast_error &e) {
0265                 return py::str(e.what()).release().ptr();
0266             }
0267             return py::str().release().ptr();
0268         };
0269 
0270         auto *def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
0271         py::capsule def_capsule(def,
0272                                 [](void *ptr) { delete reinterpret_cast<PyMethodDef *>(ptr); });
0273         return py::reinterpret_steal<py::object>(
0274             PyCFunction_NewEx(def, def_capsule.ptr(), m.ptr()));
0275     }());
0276 
0277     // test_operator_new_delete
0278     struct HasOpNewDel {
0279         std::uint64_t i;
0280         static void *operator new(size_t s) {
0281             py::print("A new", s);
0282             return ::operator new(s);
0283         }
0284         static void *operator new(size_t s, void *ptr) {
0285             py::print("A placement-new", s);
0286             return ptr;
0287         }
0288         static void operator delete(void *p) {
0289             py::print("A delete");
0290             return ::operator delete(p);
0291         }
0292     };
0293     struct HasOpNewDelSize {
0294         std::uint32_t i;
0295         static void *operator new(size_t s) {
0296             py::print("B new", s);
0297             return ::operator new(s);
0298         }
0299         static void *operator new(size_t s, void *ptr) {
0300             py::print("B placement-new", s);
0301             return ptr;
0302         }
0303         static void operator delete(void *p, size_t s) {
0304             py::print("B delete", s);
0305             return ::operator delete(p);
0306         }
0307     };
0308     struct AliasedHasOpNewDelSize {
0309         std::uint64_t i;
0310         static void *operator new(size_t s) {
0311             py::print("C new", s);
0312             return ::operator new(s);
0313         }
0314         static void *operator new(size_t s, void *ptr) {
0315             py::print("C placement-new", s);
0316             return ptr;
0317         }
0318         static void operator delete(void *p, size_t s) {
0319             py::print("C delete", s);
0320             return ::operator delete(p);
0321         }
0322         virtual ~AliasedHasOpNewDelSize() = default;
0323         AliasedHasOpNewDelSize() = default;
0324         AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize &) = delete;
0325     };
0326     struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
0327         PyAliasedHasOpNewDelSize() = default;
0328         explicit PyAliasedHasOpNewDelSize(int) {}
0329         std::uint64_t j;
0330     };
0331     struct HasOpNewDelBoth {
0332         std::uint32_t i[8];
0333         static void *operator new(size_t s) {
0334             py::print("D new", s);
0335             return ::operator new(s);
0336         }
0337         static void *operator new(size_t s, void *ptr) {
0338             py::print("D placement-new", s);
0339             return ptr;
0340         }
0341         static void operator delete(void *p) {
0342             py::print("D delete");
0343             return ::operator delete(p);
0344         }
0345         static void operator delete(void *p, size_t s) {
0346             py::print("D wrong delete", s);
0347             return ::operator delete(p);
0348         }
0349     };
0350     py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
0351     py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
0352     py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
0353     py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m,
0354                                                                          "AliasedHasOpNewDelSize");
0355     aliased.def(py::init<>());
0356     aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
0357     aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
0358 
0359     // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
0360     // definition in a different compilation unit within the same module:
0361     bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
0362 
0363     // test_bind_protected_functions
0364     class ProtectedA {
0365     protected:
0366         int foo() const { return value; }
0367 
0368     private:
0369         int value = 42;
0370     };
0371 
0372     class PublicistA : public ProtectedA {
0373     public:
0374         using ProtectedA::foo;
0375     };
0376 
0377     py::class_<ProtectedA>(m, "ProtectedA").def(py::init<>()).def("foo", &PublicistA::foo);
0378 
0379     class ProtectedB {
0380     public:
0381         virtual ~ProtectedB() = default;
0382         ProtectedB() = default;
0383         ProtectedB(const ProtectedB &) = delete;
0384 
0385     protected:
0386         virtual int foo() const { return value; }
0387         virtual void *void_foo() { return static_cast<void *>(&value); }
0388         virtual void *get_self() { return static_cast<void *>(this); }
0389 
0390     private:
0391         int value = 42;
0392     };
0393 
0394     class TrampolineB : public ProtectedB {
0395     public:
0396         int foo() const override { PYBIND11_OVERRIDE(int, ProtectedB, foo, ); }
0397         void *void_foo() override { PYBIND11_OVERRIDE(void *, ProtectedB, void_foo, ); }
0398         void *get_self() override { PYBIND11_OVERRIDE(void *, ProtectedB, get_self, ); }
0399     };
0400 
0401     class PublicistB : public ProtectedB {
0402     public:
0403         // [workaround(intel)] = default does not work here
0404         // Removing or defaulting this destructor results in linking errors with the Intel compiler
0405         // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)
0406         ~PublicistB() override{}; // NOLINT(modernize-use-equals-default)
0407         using ProtectedB::foo;
0408         using ProtectedB::get_self;
0409         using ProtectedB::void_foo;
0410     };
0411 
0412     m.def("read_foo", [](const void *original) {
0413         const int *ptr = reinterpret_cast<const int *>(original);
0414         return *ptr;
0415     });
0416 
0417     m.def("pointers_equal",
0418           [](const void *original, const void *comparison) { return original == comparison; });
0419 
0420     py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
0421         .def(py::init<>())
0422         .def("foo", &PublicistB::foo)
0423         .def("void_foo", &PublicistB::void_foo)
0424         .def("get_self", &PublicistB::get_self);
0425 
0426     // test_brace_initialization
0427     struct BraceInitialization {
0428         int field1;
0429         std::string field2;
0430     };
0431 
0432     py::class_<BraceInitialization>(m, "BraceInitialization")
0433         .def(py::init<int, const std::string &>())
0434         .def_readwrite("field1", &BraceInitialization::field1)
0435         .def_readwrite("field2", &BraceInitialization::field2);
0436     // We *don't* want to construct using braces when the given constructor argument maps to a
0437     // constructor, because brace initialization could go to the wrong place (in particular when
0438     // there is also an `initializer_list<T>`-accept constructor):
0439     py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
0440         .def(py::init<std::vector<int>>())
0441         .def_readonly("vec", &NoBraceInitialization::vec);
0442 
0443     // test_reentrant_implicit_conversion_failure
0444     // #1035: issue with runaway reentrant implicit conversion
0445     struct BogusImplicitConversion {
0446         BogusImplicitConversion(const BogusImplicitConversion &) = default;
0447     };
0448 
0449     py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
0450         .def(py::init<const BogusImplicitConversion &>());
0451 
0452     py::implicitly_convertible<int, BogusImplicitConversion>();
0453 
0454     // test_qualname
0455     // #1166: nested class docstring doesn't show nested name
0456     // Also related: tests that __qualname__ is set properly
0457     struct NestBase {};
0458     struct Nested {};
0459     py::class_<NestBase> base(m, "NestBase");
0460     base.def(py::init<>());
0461     py::class_<Nested>(base, "Nested")
0462         .def(py::init<>())
0463         .def("fn", [](Nested &, int, NestBase &, Nested &) {})
0464         .def(
0465             "fa", [](Nested &, int, NestBase &, Nested &) {}, "a"_a, "b"_a, "c"_a);
0466     base.def("g", [](NestBase &, Nested &) {});
0467     base.def("h", []() { return NestBase(); });
0468 
0469     // test_error_after_conversion
0470     // The second-pass path through dispatcher() previously didn't
0471     // remember which overload was used, and would crash trying to
0472     // generate a useful error message
0473 
0474     struct NotRegistered {};
0475     struct StringWrapper {
0476         std::string str;
0477     };
0478     m.def("test_error_after_conversions", [](int) {});
0479     m.def("test_error_after_conversions",
0480           [](const StringWrapper &) -> NotRegistered { return {}; });
0481     py::class_<StringWrapper>(m, "StringWrapper").def(py::init<std::string>());
0482     py::implicitly_convertible<std::string, StringWrapper>();
0483 
0484 #if defined(PYBIND11_CPP17)
0485     struct alignas(1024) Aligned {
0486         std::uintptr_t ptr() const { return (uintptr_t) this; }
0487     };
0488     py::class_<Aligned>(m, "Aligned").def(py::init<>()).def("ptr", &Aligned::ptr);
0489 #endif
0490 
0491     // test_final
0492     struct IsFinal final {};
0493     py::class_<IsFinal>(m, "IsFinal", py::is_final());
0494 
0495     // test_non_final_final
0496     struct IsNonFinalFinal {};
0497     py::class_<IsNonFinalFinal>(m, "IsNonFinalFinal", py::is_final());
0498 
0499     // test_exception_rvalue_abort
0500     struct PyPrintDestructor {
0501         PyPrintDestructor() = default;
0502         ~PyPrintDestructor() { py::print("Print from destructor"); }
0503         void throw_something() { throw std::runtime_error("error"); }
0504     };
0505     py::class_<PyPrintDestructor>(m, "PyPrintDestructor")
0506         .def(py::init<>())
0507         .def("throw_something", &PyPrintDestructor::throw_something);
0508 
0509     // test_multiple_instances_with_same_pointer
0510     struct SamePointer {};
0511     static SamePointer samePointer;
0512     py::class_<SamePointer, std::unique_ptr<SamePointer, py::nodelete>>(m, "SamePointer")
0513         .def(py::init([]() { return &samePointer; }));
0514 
0515     struct Empty {};
0516     py::class_<Empty>(m, "Empty").def(py::init<>());
0517 
0518     // test_base_and_derived_nested_scope
0519     struct BaseWithNested {
0520         struct Nested {};
0521     };
0522 
0523     struct DerivedWithNested : BaseWithNested {
0524         struct Nested {};
0525     };
0526 
0527     py::class_<BaseWithNested> baseWithNested_class(m, "BaseWithNested");
0528     py::class_<DerivedWithNested, BaseWithNested> derivedWithNested_class(m, "DerivedWithNested");
0529     py::class_<BaseWithNested::Nested>(baseWithNested_class, "Nested")
0530         .def_static("get_name", []() { return "BaseWithNested::Nested"; });
0531     py::class_<DerivedWithNested::Nested>(derivedWithNested_class, "Nested")
0532         .def_static("get_name", []() { return "DerivedWithNested::Nested"; });
0533 
0534     // test_register_duplicate_class
0535     struct Duplicate {};
0536     struct OtherDuplicate {};
0537     struct DuplicateNested {};
0538     struct OtherDuplicateNested {};
0539 
0540     m.def("register_duplicate_class_name", [](const py::module_ &m) {
0541         py::class_<Duplicate>(m, "Duplicate");
0542         py::class_<OtherDuplicate>(m, "Duplicate");
0543     });
0544     m.def("register_duplicate_class_type", [](const py::module_ &m) {
0545         py::class_<OtherDuplicate>(m, "OtherDuplicate");
0546         py::class_<OtherDuplicate>(m, "YetAnotherDuplicate");
0547     });
0548     m.def("register_duplicate_nested_class_name", [](const py::object &gt) {
0549         py::class_<DuplicateNested>(gt, "DuplicateNested");
0550         py::class_<OtherDuplicateNested>(gt, "DuplicateNested");
0551     });
0552     m.def("register_duplicate_nested_class_type", [](const py::object &gt) {
0553         py::class_<OtherDuplicateNested>(gt, "OtherDuplicateNested");
0554         py::class_<OtherDuplicateNested>(gt, "YetAnotherDuplicateNested");
0555     });
0556 
0557     test_class::pr4220_tripped_over_this::bind_empty0(m);
0558 }
0559 
0560 template <int N>
0561 class BreaksBase {
0562 public:
0563     virtual ~BreaksBase() = default;
0564     BreaksBase() = default;
0565     BreaksBase(const BreaksBase &) = delete;
0566 };
0567 template <int N>
0568 class BreaksTramp : public BreaksBase<N> {};
0569 // These should all compile just fine:
0570 using DoesntBreak1 = py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>>;
0571 using DoesntBreak2 = py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>>;
0572 using DoesntBreak3 = py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>>;
0573 using DoesntBreak4 = py::class_<BreaksBase<4>, BreaksTramp<4>>;
0574 using DoesntBreak5 = py::class_<BreaksBase<5>>;
0575 using DoesntBreak6 = py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>>;
0576 using DoesntBreak7 = py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>>;
0577 using DoesntBreak8 = py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>>;
0578 #define CHECK_BASE(N)                                                                             \
0579     static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<(N)>>::value,            \
0580                   "DoesntBreak" #N " has wrong type!")
0581 CHECK_BASE(1);
0582 CHECK_BASE(2);
0583 CHECK_BASE(3);
0584 CHECK_BASE(4);
0585 CHECK_BASE(5);
0586 CHECK_BASE(6);
0587 CHECK_BASE(7);
0588 CHECK_BASE(8);
0589 #define CHECK_ALIAS(N)                                                                            \
0590     static_assert(                                                                                \
0591         DoesntBreak##N::has_alias                                                                 \
0592             && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<(N)>>::value,        \
0593         "DoesntBreak" #N " has wrong type_alias!")
0594 #define CHECK_NOALIAS(N)                                                                          \
0595     static_assert(!DoesntBreak##N::has_alias                                                      \
0596                       && std::is_void<typename DoesntBreak##N::type_alias>::value,                \
0597                   "DoesntBreak" #N " has type alias, but shouldn't!")
0598 CHECK_ALIAS(1);
0599 CHECK_ALIAS(2);
0600 CHECK_NOALIAS(3);
0601 CHECK_ALIAS(4);
0602 CHECK_NOALIAS(5);
0603 CHECK_ALIAS(6);
0604 CHECK_ALIAS(7);
0605 CHECK_NOALIAS(8);
0606 #define CHECK_HOLDER(N, TYPE)                                                                     \
0607     static_assert(std::is_same<typename DoesntBreak##N::holder_type,                              \
0608                                std::TYPE##_ptr<BreaksBase<(N)>>>::value,                          \
0609                   "DoesntBreak" #N " has wrong holder_type!")
0610 CHECK_HOLDER(1, unique);
0611 CHECK_HOLDER(2, unique);
0612 CHECK_HOLDER(3, unique);
0613 CHECK_HOLDER(4, unique);
0614 CHECK_HOLDER(5, unique);
0615 CHECK_HOLDER(6, shared);
0616 CHECK_HOLDER(7, shared);
0617 CHECK_HOLDER(8, shared);
0618 
0619 // There's no nice way to test that these fail because they fail to compile; leave them here,
0620 // though, so that they can be manually tested by uncommenting them (and seeing that compilation
0621 // failures occurs).
0622 
0623 // We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
0624 #define CHECK_BROKEN(N)                                                                           \
0625     static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-(N)>>::value,                \
0626                   "Breaks1 has wrong type!");
0627 
0628 #ifdef PYBIND11_NEVER_DEFINED_EVER
0629 // Two holder classes:
0630 typedef py::
0631     class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>>
0632         Breaks1;
0633 CHECK_BROKEN(1);
0634 // Two aliases:
0635 typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
0636 CHECK_BROKEN(2);
0637 // Holder + 2 aliases
0638 typedef py::
0639     class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>>
0640         Breaks3;
0641 CHECK_BROKEN(3);
0642 // Alias + 2 holders
0643 typedef py::class_<BreaksBase<-4>,
0644                    std::unique_ptr<BreaksBase<-4>>,
0645                    BreaksTramp<-4>,
0646                    std::shared_ptr<BreaksBase<-4>>>
0647     Breaks4;
0648 CHECK_BROKEN(4);
0649 // Invalid option (not a subclass or holder)
0650 typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
0651 CHECK_BROKEN(5);
0652 // Invalid option: multiple inheritance not supported:
0653 template <>
0654 struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
0655 typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
0656 CHECK_BROKEN(8);
0657 #endif