How to prevent std::function to bool conversion in C++ function overloading?
such as
class Object final {
public:
Object(bool boolean) : type_(22) {} //#1
Object(const std::function<int(int*, int)> value) : type_(11) {} //#2
int rettype() { return type_; };
private:
int type_;
};
int Println(int *args, int nargs) {
printf("Println\n");
return 0;
}
int main() {
cout << Object(Println).rettype() << endl; // 22
cout << Object(std::function<int(int*, int)>(Println)).rettype() << endl; // 11
}
I want to call #2 through Object(Println) instead of Object(std::function<int(int*, int)>(Println)),but the result is that #1 is called
How should I achieve this?
The modern C++ solution here would be
Object::Object(std::invocable<int*, int> auto f)
You don't care exactly what the type of f is - that's clear from the fact that you consider std::function<int(int*, int)> and int(*)(int*, int)> interchangeable. std::invocable is slightly more general than that: it says anything callable is also OK. A lambda would also work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With