我尝试在 pybind11 中使用模板 based on this demo。错误
>>> 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
为什么myadd不能导入,add可以?我可以使用 int、double、void 等基本函数,但每当我尝试使用任何更复杂的结构(如模板或 shared_ptr)时,都会再次出现此错误(即使我只是从文档中复制粘贴示例)。
源代码
#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>);
}
您需要显式实例化函数
template int myadd<int>(int a, int b);
template float myadd<float>(float a, float b);
否则没有什么可以取地址的。见这里,注意你也可以使用
std::addressof
.