简化在Pybind11中为C ++模板类生成包装器类的步骤:模板声明不能出现在块作用域中

时间:2020-05-13 15:34:19

标签: python c++ pybind11

我正在尝试简化在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>
      |     ^~~~~~~~

2 个答案:

答案 0 :(得分:2)

就像该错误表明您不能在块作用域内使用模板声明一样(显然您在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>

不建议依赖可传递包含。

答案 1 :(得分:1)

我想出了以下使用宏的解决方法

template<class T>
class Foo {
public:
    Foo(T bar) : bar_(bar) {}
    void print() {
        std::cout << "Type id: " << typeid(T).name() << '\n';
    }
private:
    T bar_;
};

#define DECLARE_FOO(T, NAME) { \
  py::class_<Foo<T> >(m, (std::string("Foo")+NAME).c_str()) \
    .def(py::init< T >()) \
    .def("print", &Foo<T>::print); \
}

PYBIND11_MODULE(example, m) {
  DECLARE_FOO(int, "int");
  DECLARE_FOO(float, "float");
}

它似乎正在工作,但是我不确定此宏是否足够健壮。