Search code examples
c++pybind11

Strange C++ syntax: setting function output with some value


I was trying to get pybind11 up and running, and I ran across some strange syntax:

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring
    m.attr("the_answer") = 42;
    m.def("add", &add, "A function which adds two numbers");
}

I figured that PYBIND11_MODULE is a macro, and that pybind11 should execute everything inside the code block to setup a Python module. However, the syntax at m.doc() = ... and m.attr("the_answer") = 42 looks strange. The code does compile on my machine though. My question is, what are they and do they have a name?


Solution

  • It is returning references to objects. Check this example:

    class A {
    private:
       int var;
    public: 
       int& internal_var() { return var; }
    };
    
    ...
    
    A a;
    a.internal_var() = 1;