【问题标题】:pybind11 implicitly_convertible does not workpybind11 implicitly_convertible 不起作用
【发布时间】:2021-11-17 07:58:47
【问题描述】:

我正在努力使最简单的示例工作。这是我的代码:

// example.cpp

#include <pybind11/pybind11.h>
namespace py = pybind11;

class B {
public:
    int b;
};

class A {
public:
    int a;
    A(int a) :a(a) {}
    A(B b) { a = b.b; }
};

void fn(A) {}

PYBIND11_MODULE(example, m) {

    py::class_<A>(m, "A")
        .def(
            py::init<int>(),
            py::arg("a") = 1
        );

    py::class_<B>(m, "B")
        .def(
            py::init<int>(),
            py::arg("b") = 2
        );

    py::implicitly_convertible<A, B>();

    m.def("fn", &fn,
        py::arg("a")
    );
}
# test.py

from example import *

a = A()
b = B()

fn(b)

它构建得很好,但输出是:

$ python3.9 test.py 
Traceback (most recent call last):
  File "/pybindtest/test.py", line 8, in <module>
    fn(b)
TypeError: fn(): incompatible function arguments. The following argument types are supported:
    1. (a: example.A) -> None

Invoked with: <example.B object at 0x7fc3016a83b0>

我以为我已经实现了这里描述的演示案例:https://pybind11.readthedocs.io/en/stable/advanced/classes.html#implicit-conversions

我还尝试将其添加到 A 的 init 中: .def(py::init&lt;B&gt;()) 但没有运气。

我在这里缺少什么? 提前致谢!

解决方案:

原来它必须是 py::implicitly_convertible&lt;B, A&gt;();(所以 A 和 B 交换了)并且还需要 .def(py::init&lt;B&gt;())

【问题讨论】:

    标签: implicit-conversion pybind11


    【解决方案1】:

    您混淆了传递给py::implicitly_convertible 的模板参数的顺序。应该是py::implicitly_convertible&lt;convert_from, convert_to&gt;,在你的情况下应该是

    py::implicitly_convertible<B, A>
    

    【讨论】:

    • 谢谢!我实际上在添加.def(py::init&lt;B&gt;()) 行之前尝试过:P,结果两者都需要。问题是,在我的实际代码中,我希望隐式转换不被定义为构造函数,而是在 B 中定义为operator A()(所以我不会松散初始化列表构造)。如果存在.def(py::init&lt;B&gt;()),这仍然有效,但它在语义上有些错误,因为该构造函数实际上并不存在。你知道这还好吗?
    • @Mircode 我明白了。我不确定是否有“更清洁”的方式。我尝试修改代码,但如果不像你一样初始化“假”构造函数,我就无法让它工作。对不起!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2020-10-07
    • 1970-01-01
    • 2019-11-16
    • 2019-05-18
    相关资源
    最近更新 更多