You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.6 KiB

  1. /*
  2. tests/test_alias_initialization.cpp -- test cases and example of different trampoline
  3. initialization modes
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>, Jason Rhinelander <jason@imaginary.ca>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #include "pybind11_tests.h"
  9. test_initializer alias_initialization([](py::module &m) {
  10. // don't invoke Python dispatch classes by default when instantiating C++ classes that were not
  11. // extended on the Python side
  12. struct A {
  13. virtual ~A() {}
  14. virtual void f() { py::print("A.f()"); }
  15. };
  16. struct PyA : A {
  17. PyA() { py::print("PyA.PyA()"); }
  18. ~PyA() { py::print("PyA.~PyA()"); }
  19. void f() override {
  20. py::print("PyA.f()");
  21. PYBIND11_OVERLOAD(void, A, f);
  22. }
  23. };
  24. auto call_f = [](A *a) { a->f(); };
  25. py::class_<A, PyA>(m, "A")
  26. .def(py::init<>())
  27. .def("f", &A::f);
  28. m.def("call_f", call_f);
  29. // ... unless we explicitly request it, as in this example:
  30. struct A2 {
  31. virtual ~A2() {}
  32. virtual void f() { py::print("A2.f()"); }
  33. };
  34. struct PyA2 : A2 {
  35. PyA2() { py::print("PyA2.PyA2()"); }
  36. ~PyA2() { py::print("PyA2.~PyA2()"); }
  37. void f() override {
  38. py::print("PyA2.f()");
  39. PYBIND11_OVERLOAD(void, A2, f);
  40. }
  41. };
  42. py::class_<A2, PyA2>(m, "A2")
  43. .def(py::init_alias<>())
  44. .def("f", &A2::f);
  45. m.def("call_f", [](A2 *a2) { a2->f(); });
  46. });