implicit-conversion - pybind11 implicitly_convertible 不起作用

标签 implicit-conversion pybind11

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

// 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<B>())但没有运气。
我在这里错过了什么?
提前致谢!
解决方案:
原来它必须是 py::implicitly_convertible<B, A>(); (所以 A 和 B 交换了)和 .def(py::init<B>())也是需要的。

最佳答案

您混淆了传递给 py::implicitly_convertible 的模板参数的顺序.应该是 py::implicitly_convertible<convert_from, convert_to> ,在你的情况下应该是

py::implicitly_convertible<B, A>

关于implicit-conversion - pybind11 implicitly_convertible 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70000680/

相关文章:

c# - 有没有办法在 C# 中进行动态隐式类型转换?

c# - 什么时候应该在 C# 中定义(显式或隐式)转换运算符?

c - C如何处理混合精度运算

c# - 你能用隐式转换满足通用约束吗?

python - 如何使用 pybind11 提供默认枚举值?

scala - Scala中隐式参数的通用容器的隐式转换

python - pybind11 - ImportError : undefined symbol: _Py_ZeroStruct

python - 如何使用 pybind11 正确编译 c++ 代码

c++ - 错误 C1083 无法打开包含文件 : 'pybind11/pybind11.h' : No such file or directory

c++ - 尝试使用gcc构建pybind11项目时获取 undefined reference