【发布时间】:2020-05-13 15:34:19
【问题描述】:
我正在尝试简化在 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>
| ^~~~~~~~
【问题讨论】: