我试图简化在Pybind11中为C++模板类生成包装器类的过程。这是一个显示问题的最小示例(以下this回答):
#include <pybind11/pybind11.h>
#include <iostream>
namespace py = pybind11;
template<class T>
class Foo {
public:
Foo(T bar) : bar_(bar) {}
void print() {
std::cout << "Type id: " << typeid(T).name() << '\n';
}
private:
T bar_;
};
PYBIND11_MODULE(example, m) {
template<typename T>
void declare_foo(py::module &m, std::string &typestr) {
using Class = Foo<T>;
std::string pyclass_name = std::string("Foo") + typestr;
py::class_<Class>(m, pyclass_name.c_str())
.def(py::init< T >())
.def("print", &Class::print);
}
declare_foo<int>(m, "Int");
declare_foo<double>(m, "Double");
# More similar declarations follow here...
}
当我用以下命令编译时:
g++ -O3 -Wall -shared -std=c++17 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
我得到错误:
example.cpp: In function ‘void pybind11_init_example(pybind11::module&)’:
example.cpp:18:5: error: a template declaration cannot appear at block scope
18 | template<typename T>
| ^~~~~~~~
最佳答案
像错误提示一样,您不能在块范围内使用模板声明(显然您在https://en.cppreference.com/w/cpp/language/scope中)。只需将其移到外部并通过const引用(或值)捕获字符串参数即可。
将代码更改为
template<typename T>
void declare_foo(py::module &m, const std::string &typestr) {
using Class = Foo<T>;
std::string pyclass_name = std::string("Foo") + typestr;
py::class_<Class>(m, pyclass_name.c_str())
.def(py::init< T >())
.def("print", &Class::print);
}
PYBIND11_MODULE(example, m) {
declare_foo<int>(m, "Int");
declare_foo<double>(m, "Double");
}
作品。
作为旁注,您还应该
#include <string>
不建议依赖可传递包含。
关于python - 简化在Pybind11中为C++模板类生成包装器类的步骤:模板声明不能出现在 block 作用域中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61778729/