test_virtual_functions.cpp revision 12391:ceeca8b41e4b
1/*
2    tests/test_virtual_functions.cpp -- overriding virtual functions from Python
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#include "pybind11_tests.h"
11#include "constructor_stats.h"
12#include <pybind11/functional.h>
13
14/* This is an example class that we'll want to be able to extend from Python */
15class ExampleVirt  {
16public:
17    ExampleVirt(int state) : state(state) { print_created(this, state); }
18    ExampleVirt(const ExampleVirt &e) : state(e.state) { print_copy_created(this); }
19    ExampleVirt(ExampleVirt &&e) : state(e.state) { print_move_created(this); e.state = 0; }
20    ~ExampleVirt() { print_destroyed(this); }
21
22    virtual int run(int value) {
23        py::print("Original implementation of "
24                  "ExampleVirt::run(state={}, value={}, str1={}, str2={})"_s.format(state, value, get_string1(), *get_string2()));
25        return state + value;
26    }
27
28    virtual bool run_bool() = 0;
29    virtual void pure_virtual() = 0;
30
31    // Returning a reference/pointer to a type converted from python (numbers, strings, etc.) is a
32    // bit trickier, because the actual int& or std::string& or whatever only exists temporarily, so
33    // we have to handle it specially in the trampoline class (see below).
34    virtual const std::string &get_string1() { return str1; }
35    virtual const std::string *get_string2() { return &str2; }
36
37private:
38    int state;
39    const std::string str1{"default1"}, str2{"default2"};
40};
41
42/* This is a wrapper class that must be generated */
43class PyExampleVirt : public ExampleVirt {
44public:
45    using ExampleVirt::ExampleVirt; /* Inherit constructors */
46
47    int run(int value) override {
48        /* Generate wrapping code that enables native function overloading */
49        PYBIND11_OVERLOAD(
50            int,         /* Return type */
51            ExampleVirt, /* Parent class */
52            run,         /* Name of function */
53            value        /* Argument(s) */
54        );
55    }
56
57    bool run_bool() override {
58        PYBIND11_OVERLOAD_PURE(
59            bool,         /* Return type */
60            ExampleVirt,  /* Parent class */
61            run_bool,     /* Name of function */
62                          /* This function has no arguments. The trailing comma
63                             in the previous line is needed for some compilers */
64        );
65    }
66
67    void pure_virtual() override {
68        PYBIND11_OVERLOAD_PURE(
69            void,         /* Return type */
70            ExampleVirt,  /* Parent class */
71            pure_virtual, /* Name of function */
72                          /* This function has no arguments. The trailing comma
73                             in the previous line is needed for some compilers */
74        );
75    }
76
77    // We can return reference types for compatibility with C++ virtual interfaces that do so, but
78    // note they have some significant limitations (see the documentation).
79    const std::string &get_string1() override {
80        PYBIND11_OVERLOAD(
81            const std::string &, /* Return type */
82            ExampleVirt,         /* Parent class */
83            get_string1,         /* Name of function */
84                                 /* (no arguments) */
85        );
86    }
87
88    const std::string *get_string2() override {
89        PYBIND11_OVERLOAD(
90            const std::string *, /* Return type */
91            ExampleVirt,         /* Parent class */
92            get_string2,         /* Name of function */
93                                 /* (no arguments) */
94        );
95    }
96
97};
98
99class NonCopyable {
100public:
101    NonCopyable(int a, int b) : value{new int(a*b)} { print_created(this, a, b); }
102    NonCopyable(NonCopyable &&o) { value = std::move(o.value); print_move_created(this); }
103    NonCopyable(const NonCopyable &) = delete;
104    NonCopyable() = delete;
105    void operator=(const NonCopyable &) = delete;
106    void operator=(NonCopyable &&) = delete;
107    std::string get_value() const {
108        if (value) return std::to_string(*value); else return "(null)";
109    }
110    ~NonCopyable() { print_destroyed(this); }
111
112private:
113    std::unique_ptr<int> value;
114};
115
116// This is like the above, but is both copy and movable.  In effect this means it should get moved
117// when it is not referenced elsewhere, but copied if it is still referenced.
118class Movable {
119public:
120    Movable(int a, int b) : value{a+b} { print_created(this, a, b); }
121    Movable(const Movable &m) { value = m.value; print_copy_created(this); }
122    Movable(Movable &&m) { value = std::move(m.value); print_move_created(this); }
123    std::string get_value() const { return std::to_string(value); }
124    ~Movable() { print_destroyed(this); }
125private:
126    int value;
127};
128
129class NCVirt {
130public:
131    virtual NonCopyable get_noncopyable(int a, int b) { return NonCopyable(a, b); }
132    virtual Movable get_movable(int a, int b) = 0;
133
134    std::string print_nc(int a, int b) { return get_noncopyable(a, b).get_value(); }
135    std::string print_movable(int a, int b) { return get_movable(a, b).get_value(); }
136};
137class NCVirtTrampoline : public NCVirt {
138#if !defined(__INTEL_COMPILER)
139    NonCopyable get_noncopyable(int a, int b) override {
140        PYBIND11_OVERLOAD(NonCopyable, NCVirt, get_noncopyable, a, b);
141    }
142#endif
143    Movable get_movable(int a, int b) override {
144        PYBIND11_OVERLOAD_PURE(Movable, NCVirt, get_movable, a, b);
145    }
146};
147
148struct Base {
149    /* for some reason MSVC2015 can't compile this if the function is pure virtual */
150    virtual std::string dispatch() const { return {}; };
151    virtual ~Base() = default;
152};
153
154struct DispatchIssue : Base {
155    virtual std::string dispatch() const {
156        PYBIND11_OVERLOAD_PURE(std::string, Base, dispatch, /* no arguments */);
157    }
158};
159
160// Forward declaration (so that we can put the main tests here; the inherited virtual approaches are
161// rather long).
162void initialize_inherited_virtuals(py::module &m);
163
164TEST_SUBMODULE(virtual_functions, m) {
165    // test_override
166    py::class_<ExampleVirt, PyExampleVirt>(m, "ExampleVirt")
167        .def(py::init<int>())
168        /* Reference original class in function definitions */
169        .def("run", &ExampleVirt::run)
170        .def("run_bool", &ExampleVirt::run_bool)
171        .def("pure_virtual", &ExampleVirt::pure_virtual);
172
173    py::class_<NonCopyable>(m, "NonCopyable")
174        .def(py::init<int, int>());
175
176    py::class_<Movable>(m, "Movable")
177        .def(py::init<int, int>());
178
179    // test_move_support
180#if !defined(__INTEL_COMPILER)
181    py::class_<NCVirt, NCVirtTrampoline>(m, "NCVirt")
182        .def(py::init<>())
183        .def("get_noncopyable", &NCVirt::get_noncopyable)
184        .def("get_movable", &NCVirt::get_movable)
185        .def("print_nc", &NCVirt::print_nc)
186        .def("print_movable", &NCVirt::print_movable);
187#endif
188
189    m.def("runExampleVirt", [](ExampleVirt *ex, int value) { return ex->run(value); });
190    m.def("runExampleVirtBool", [](ExampleVirt* ex) { return ex->run_bool(); });
191    m.def("runExampleVirtVirtual", [](ExampleVirt *ex) { ex->pure_virtual(); });
192
193    m.def("cstats_debug", &ConstructorStats::get<ExampleVirt>);
194    initialize_inherited_virtuals(m);
195
196    // test_alias_delay_initialization1
197    // don't invoke Python dispatch classes by default when instantiating C++ classes
198    // that were not extended on the Python side
199    struct A {
200        virtual ~A() {}
201        virtual void f() { py::print("A.f()"); }
202    };
203
204    struct PyA : A {
205        PyA() { py::print("PyA.PyA()"); }
206        ~PyA() { py::print("PyA.~PyA()"); }
207
208        void f() override {
209            py::print("PyA.f()");
210            PYBIND11_OVERLOAD(void, A, f);
211        }
212    };
213
214    py::class_<A, PyA>(m, "A")
215        .def(py::init<>())
216        .def("f", &A::f);
217
218    m.def("call_f", [](A *a) { a->f(); });
219
220    // test_alias_delay_initialization2
221    // ... unless we explicitly request it, as in this example:
222    struct A2 {
223        virtual ~A2() {}
224        virtual void f() { py::print("A2.f()"); }
225    };
226
227    struct PyA2 : A2 {
228        PyA2() { py::print("PyA2.PyA2()"); }
229        ~PyA2() { py::print("PyA2.~PyA2()"); }
230        void f() override {
231            py::print("PyA2.f()");
232            PYBIND11_OVERLOAD(void, A2, f);
233        }
234    };
235
236    py::class_<A2, PyA2>(m, "A2")
237        .def(py::init_alias<>())
238        .def(py::init([](int) { return new PyA2(); }))
239        .def("f", &A2::f);
240
241    m.def("call_f", [](A2 *a2) { a2->f(); });
242
243    // test_dispatch_issue
244    // #159: virtual function dispatch has problems with similar-named functions
245    py::class_<Base, DispatchIssue>(m, "DispatchIssue")
246        .def(py::init<>())
247        .def("dispatch", &Base::dispatch);
248
249    m.def("dispatch_issue_go", [](const Base * b) { return b->dispatch(); });
250
251    // test_override_ref
252    // #392/397: overridding reference-returning functions
253    class OverrideTest {
254    public:
255        struct A { std::string value = "hi"; };
256        std::string v;
257        A a;
258        explicit OverrideTest(const std::string &v) : v{v} {}
259        virtual std::string str_value() { return v; }
260        virtual std::string &str_ref() { return v; }
261        virtual A A_value() { return a; }
262        virtual A &A_ref() { return a; }
263        virtual ~OverrideTest() = default;
264    };
265
266    class PyOverrideTest : public OverrideTest {
267    public:
268        using OverrideTest::OverrideTest;
269        std::string str_value() override { PYBIND11_OVERLOAD(std::string, OverrideTest, str_value); }
270        // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
271        // to a python numeric value, since we only copy values in the numeric type caster:
272//      std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
273        // But we can work around it like this:
274    private:
275        std::string _tmp;
276        std::string str_ref_helper() { PYBIND11_OVERLOAD(std::string, OverrideTest, str_ref); }
277    public:
278        std::string &str_ref() override { return _tmp = str_ref_helper(); }
279
280        A A_value() override { PYBIND11_OVERLOAD(A, OverrideTest, A_value); }
281        A &A_ref() override { PYBIND11_OVERLOAD(A &, OverrideTest, A_ref); }
282    };
283
284    py::class_<OverrideTest::A>(m, "OverrideTest_A")
285        .def_readwrite("value", &OverrideTest::A::value);
286    py::class_<OverrideTest, PyOverrideTest>(m, "OverrideTest")
287        .def(py::init<const std::string &>())
288        .def("str_value", &OverrideTest::str_value)
289//      .def("str_ref", &OverrideTest::str_ref)
290        .def("A_value", &OverrideTest::A_value)
291        .def("A_ref", &OverrideTest::A_ref);
292}
293
294
295// Inheriting virtual methods.  We do two versions here: the repeat-everything version and the
296// templated trampoline versions mentioned in docs/advanced.rst.
297//
298// These base classes are exactly the same, but we technically need distinct
299// classes for this example code because we need to be able to bind them
300// properly (pybind11, sensibly, doesn't allow us to bind the same C++ class to
301// multiple python classes).
302class A_Repeat {
303#define A_METHODS \
304public: \
305    virtual int unlucky_number() = 0; \
306    virtual std::string say_something(unsigned times) { \
307        std::string s = ""; \
308        for (unsigned i = 0; i < times; ++i) \
309            s += "hi"; \
310        return s; \
311    } \
312    std::string say_everything() { \
313        return say_something(1) + " " + std::to_string(unlucky_number()); \
314    }
315A_METHODS
316    virtual ~A_Repeat() = default;
317};
318class B_Repeat : public A_Repeat {
319#define B_METHODS \
320public: \
321    int unlucky_number() override { return 13; } \
322    std::string say_something(unsigned times) override { \
323        return "B says hi " + std::to_string(times) + " times"; \
324    } \
325    virtual double lucky_number() { return 7.0; }
326B_METHODS
327};
328class C_Repeat : public B_Repeat {
329#define C_METHODS \
330public: \
331    int unlucky_number() override { return 4444; } \
332    double lucky_number() override { return 888; }
333C_METHODS
334};
335class D_Repeat : public C_Repeat {
336#define D_METHODS // Nothing overridden.
337D_METHODS
338};
339
340// Base classes for templated inheritance trampolines.  Identical to the repeat-everything version:
341class A_Tpl { A_METHODS; virtual ~A_Tpl() = default; };
342class B_Tpl : public A_Tpl { B_METHODS };
343class C_Tpl : public B_Tpl { C_METHODS };
344class D_Tpl : public C_Tpl { D_METHODS };
345
346
347// Inheritance approach 1: each trampoline gets every virtual method (11 in total)
348class PyA_Repeat : public A_Repeat {
349public:
350    using A_Repeat::A_Repeat;
351    int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, A_Repeat, unlucky_number, ); }
352    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, A_Repeat, say_something, times); }
353};
354class PyB_Repeat : public B_Repeat {
355public:
356    using B_Repeat::B_Repeat;
357    int unlucky_number() override { PYBIND11_OVERLOAD(int, B_Repeat, unlucky_number, ); }
358    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, B_Repeat, say_something, times); }
359    double lucky_number() override { PYBIND11_OVERLOAD(double, B_Repeat, lucky_number, ); }
360};
361class PyC_Repeat : public C_Repeat {
362public:
363    using C_Repeat::C_Repeat;
364    int unlucky_number() override { PYBIND11_OVERLOAD(int, C_Repeat, unlucky_number, ); }
365    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, C_Repeat, say_something, times); }
366    double lucky_number() override { PYBIND11_OVERLOAD(double, C_Repeat, lucky_number, ); }
367};
368class PyD_Repeat : public D_Repeat {
369public:
370    using D_Repeat::D_Repeat;
371    int unlucky_number() override { PYBIND11_OVERLOAD(int, D_Repeat, unlucky_number, ); }
372    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, D_Repeat, say_something, times); }
373    double lucky_number() override { PYBIND11_OVERLOAD(double, D_Repeat, lucky_number, ); }
374};
375
376// Inheritance approach 2: templated trampoline classes.
377//
378// Advantages:
379// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one for
380//   any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes and 11
381//   methods (repeat).
382// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and can
383//   properly inherit constructors.
384//
385// Disadvantage:
386// - the compiler must still generate and compile 14 different methods (more, even, than the 11
387//   required for the repeat approach) instead of the 6 required for MI.  (If there was no pure
388//   method (or no pure method override), the number would drop down to the same 11 as the repeat
389//   approach).
390template <class Base = A_Tpl>
391class PyA_Tpl : public Base {
392public:
393    using Base::Base; // Inherit constructors
394    int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, Base, unlucky_number, ); }
395    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, Base, say_something, times); }
396};
397template <class Base = B_Tpl>
398class PyB_Tpl : public PyA_Tpl<Base> {
399public:
400    using PyA_Tpl<Base>::PyA_Tpl; // Inherit constructors (via PyA_Tpl's inherited constructors)
401    int unlucky_number() override { PYBIND11_OVERLOAD(int, Base, unlucky_number, ); }
402    double lucky_number() override { PYBIND11_OVERLOAD(double, Base, lucky_number, ); }
403};
404// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these (we can
405// use PyB_Tpl<C_Tpl> and PyB_Tpl<D_Tpl> for the trampoline classes instead):
406/*
407template <class Base = C_Tpl> class PyC_Tpl : public PyB_Tpl<Base> {
408public:
409    using PyB_Tpl<Base>::PyB_Tpl;
410};
411template <class Base = D_Tpl> class PyD_Tpl : public PyC_Tpl<Base> {
412public:
413    using PyC_Tpl<Base>::PyC_Tpl;
414};
415*/
416
417
418void initialize_inherited_virtuals(py::module &m) {
419    // test_inherited_virtuals
420
421    // Method 1: repeat
422    py::class_<A_Repeat, PyA_Repeat>(m, "A_Repeat")
423        .def(py::init<>())
424        .def("unlucky_number", &A_Repeat::unlucky_number)
425        .def("say_something", &A_Repeat::say_something)
426        .def("say_everything", &A_Repeat::say_everything);
427    py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, "B_Repeat")
428        .def(py::init<>())
429        .def("lucky_number", &B_Repeat::lucky_number);
430    py::class_<C_Repeat, B_Repeat, PyC_Repeat>(m, "C_Repeat")
431        .def(py::init<>());
432    py::class_<D_Repeat, C_Repeat, PyD_Repeat>(m, "D_Repeat")
433        .def(py::init<>());
434
435    // test_
436    // Method 2: Templated trampolines
437    py::class_<A_Tpl, PyA_Tpl<>>(m, "A_Tpl")
438        .def(py::init<>())
439        .def("unlucky_number", &A_Tpl::unlucky_number)
440        .def("say_something", &A_Tpl::say_something)
441        .def("say_everything", &A_Tpl::say_everything);
442    py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, "B_Tpl")
443        .def(py::init<>())
444        .def("lucky_number", &B_Tpl::lucky_number);
445    py::class_<C_Tpl, B_Tpl, PyB_Tpl<C_Tpl>>(m, "C_Tpl")
446        .def(py::init<>());
447    py::class_<D_Tpl, C_Tpl, PyB_Tpl<D_Tpl>>(m, "D_Tpl")
448        .def(py::init<>());
449
450};
451