Skip to content

[QUESTION] How to overload functions with argument of bool/int #2706

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wyq730 opened this issue Dec 1, 2020 · 3 comments
Closed

[QUESTION] How to overload functions with argument of bool/int #2706

wyq730 opened this issue Dec 1, 2020 · 3 comments

Comments

@wyq730
Copy link

wyq730 commented Dec 1, 2020

How can we overload the two functions like below?

void func(int);
void func(bool);

Even if we use overload_cast, Pybind11 will treat them as the same, so these two functions will not be distinguished in the generated Python interface.

Is there any solution to this problem?

Related discussion: #1625

@YannickJadoul
Copy link
Collaborator

Please refer to the explanation in the docs. pybind11 does overload resolution if you bind multiple functions to the same name in Python, but this is a distinct concept from overload_cast:

@wyq730
Copy link
Author

wyq730 commented Dec 1, 2020

@YannickJadoul

Thanks for the reply.

Maybe the example was a little confusing, actually the two functions can have different names:

void func1(int);
void func2(bool);

And if we bind them to the same function name in Python:

m.def("func", &func1))
   .def("func", &func2));

The overload resolution will not work well. If we call func in Python with a bool argument:

func(False)

It will use the func1 under the hood. Because it doesn't require a conversion from bool to int in Python. But actually I want to use the func2.

Does this example make the question clear?

@YannickJadoul
Copy link
Collaborator

@wyq730 Right, so as I said, it's completely unrelated to overload_cast that you mention in the original issue (as explained in the docs).

The issue you yourself linked to does explain that since issubclass(bool, int), the order of overloads is crucial in this case: #1625 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants