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