c++ - Why can't the compiler resolve an overload of a std::function parameter? -
this question has answer here:
observe following example:
#include <iostream> #include <functional> #include <cstdlib> void print_wrapper(std::function<void(int)> function); void print(int param); int main(){ print_wrapper(print); return exit_success; } void print_wrapper(std::function<void(int)> function){ int = 5; function(i); } void print(int param){ std::cout << param << std::endl; }
this works correctly, , prints 5
.
now @ same example overloaded function added:
#include <iostream> #include <functional> #include <cstdlib> void print_wrapper(std::function<void(int)> function); void print(int param); void print(float param); int main(){ print_wrapper(print); return exit_success; } void print_wrapper(std::function<void(int)> function){ int = 5; function(i); } void print(int param){ std::cout << param << std::endl; } void print(float param){ std::cout << param << std::endl; }
this gives following compiler error:
main.cpp:11:22: error: cannot resolve overloaded function ‘print’ based on conversion type ‘std::function’
print_wrapper(print);
could explain why compiler can't resolve overload?
print_wrapper
expects int function-- float function shouldn't considered.
additionally, should fix this?
i recall problems occurring if typename
or left out, require me make print_wrapper
template.
print_wrapper
need function template?
i guess i'm use functionality similar this, works. example:
#include <iostream> #include <vector> #include <cstdlib> void print_wrapper(std::vector<int> param); void print(std::vector<int> param); void print(std::vector<float> param); int main(){ std::vector<int> vi{1,2,3}; std::vector<float> vf{1.0,2.0,3.0}; print(vi); //prints int print(vf); //prints float print_wrapper(vi); //prints int (no overload issue) print_wrapper(vf); //compiler error (as expected) return exit_success; } void print_wrapper(std::vector<int> param){ print(param); return; } void print(std::vector<int> param){ std::cout << "int" << std::endl; } void print(std::vector<float> param){ std::cout << "float" << std::endl; }
so think issue lies somewhere in lookup rules of actual c++ function, example uses types. thoughts?
in c++11, std::function
's constructor can take callable object, when ill-formed , cannot call object. in c++14, overload resolution fixed both functions can called int
both valid candidates.
you need explicitely request correct function:
print_wrapper(static_cast<void(*)(int)>(print))