python - 使用默认参数提升 python make_constructor

标签 python c++ boost-python

我有一个类,我想通过 shared_ptr 传递。因此,我希望使用工厂方法构建它:

py::class_<MyClass, boost::shared_ptr<MyClass>>("MyClass")
    .def("__init__", py::make_constructor(MyClass::factory))
;

这在 factory() 只接受 2 个参数时有效。但是现在我想要它取 2 或 3。所以我使用了重载宏

BOOST_PYTHON_FUNCTION_OVERLOADS(MyClass_factory_overloads, MyClass::factory, 2, 3)

但是我如何将它传递给 make_constructor

最佳答案

我认为您不需要使用工厂来创建 MyClass 的 shared_ptr。所以,只需定义多个 init 指令:

class Foo {
public:
    Foo(int, int) { std::cout << "Foo(int, int)" << std::endl; }
    Foo(int, int, int) { std::cout << "Foo(int, int, int)" << std::endl; }
};

void test(boost::shared_ptr<Foo>& foo) { std::cout << &(*foo) << std::endl; }

BOOST_PYTHON_MODULE(mylib)
{
    using namespace boost::python;

    class_<Foo, boost::shared_ptr<Foo> >("Foo", init<int, int>())
        .def(init<int, int, int>())
    ;

    def("test", test);
}

让我们测试一下:

import mylib

c2 = mylib.Foo(1,2)
Foo(int, int)

c3 = mylib.Foo(1,1,1)
Foo(int, int, int)

mylib.test(c2)
0x1521df0

mylib.test(c3)
0x1314370

c2a = c2
mylib.test(c2a)
0x1521df0 # the object has the same address of c2

关于python - 使用默认参数提升 python make_constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491098/

相关文章:

java - 在 C++、Java、C# 之间循环初始化变量作用域

python - 无法在 OS X 上使用 boost-python 编译 python 绑定(bind)

python - Cassandra 分页 : How to use get_slice to query a Cassandra 1. 2 来自 Python 使用 cql 库的数据库

python - 将远程 PDF 页面转换为 OCR 临时图像

python - 每个域/url "SSLError certificate verify failed"

c++ - 我应该丢弃 boost::python::exec 的返回值吗?

c++ - 从暴露给 Python 的 C++ 函数返回 int 或 string

python - Metasploit 未检测到exploit-db 中添加的漏洞

c++ - 使用指针反转 C++ 中的字符数组

c++ - 从 Excel 文件读取