pybind11 cannot import templates

Question:

I tried to use templates in pybind11 based on this demo. Error

>>> from example import add
>>> add(2,3)
5L
>>> from example import myadd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name myadd

Why does myadd cannot be imported while add can? I can use basic functions like int, double, void, but whenever I try to use any more complex structures like templates or shared_ptr this error occures again (even if I just copypaste examples from documentation).

Source code

#include <pybind11/pybind11.h>
#include <iostream>
#include <string>
int add(int i, int j) {
    return i + j;
}

template <class T> //template <typename T> doesn't work as well
T myadd(T a, T b) {
    return a+b;
}
namespace py = pybind11;

PYBIND11_MODULE(example, m) {
    // optional module docstring
    m.doc() = "pybind11 example plugin";

    // define add function
    m.def("add", &add, "A function which adds two numbers");
    m.def("myadd", &myadd<int>);
    m.def("myadd", &myadd<float>);
}
Asked By: Vladislav Kogan

||

Answers:

Error was occuring in Ubuntu 20.04 LTS via VirtualBox (even with newest versions of pybind, python and compilers).
Update to Ubuntu 22.04 LTS fixed the problem.

Answered By: Vladislav Kogan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.