How to register a template based function with pybind11 class or module level function? #3662
-
How to deal with such template-based functions or methods while registering them at class or module-level def?
Please let us know if you have any knowledge of this issue. @ALL @wjakob
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @Mayuresh16 , It is fairly simple: m.def("mysum", &maths::sum<int>);
m.def("mysum", &maths::sum<int, int>);
// ... and so on
// Just for good measure:)
m.def("mysum", &maths::sum<int, int, int, int, int, int, int, int, int>); And later in Python you can just call: mymodule.mysum(1)
>>> 1
mymodule.mysum(2, 3)
>>> 5
mymodule.mysum(1, 2, 3)) # won't work as there is no overload provided
>>> TypeError: mysum(): incompatible function arguments. The following argument types are supported:
>>> 1. (arg0: int) -> int
>>> 2. (arg0: int, arg1: int) -> int
>>> 3. (arg0: int, arg1: int, arg2: int, arg3: int, arg4: int, arg5: int, arg6: int, arg7: int, arg8: int) -> int
mymodule.mysum(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> 45 But it is impossible to bind variadic function with "unrestrained" number of arguments. Sadly without any compilation time information about number of arguments you won't be able to. However there is something called m.def("mysum_with_args", [](py::args args)
{
int sum = 0;
for (auto it : args)
{
sum += it.cast<int>();
}
return sum;
}); mymodule.mysum_with_args(2)
>>> 2
mymodule.mysum_with_args(2, 2, 2)
>>> 6
mymodule.mysum_with_args(2, 2, 2, 2, 2)
>>> 10 That is the best solution to my knowledge. You either use Hope this helps! |
Beta Was this translation helpful? Give feedback.
Hi @Mayuresh16 ,
It is fairly simple:
And later in Python you can just call: