mercredi 22 avril 2015

Why can't the compiler resolve an overload of a std::function parameter? [duplicate]

This question already has an answer here:

Observe the 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 i = 5;
  function(i);
}
void Print(int param){
  std::cout << param << std::endl;
}

This works correctly, and prints 5.


Now look at the same example with an 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 i = 5;
  function(i);
}
void Print(int param){
  std::cout << param << std::endl;
}
void Print(float param){
  std::cout << param << std::endl;
}

This gives the following compiler error:

main.cpp:11:22: error: cannot resolve overloaded function ‘Print’ based on conversion to type ‘std::function’
Print_Wrapper(Print);

Could some explain why the compiler can't resolve the overload?
Print_Wrapper only expects an int function-- the float function shouldn't even be considered.


Additionally, what should I do to fix this?

I recall problems like this occurring if a typename or something was left out, but then that would require me to make Print_Wrapper a template.
Does Print_Wrapper need to be a function template?

I guess I'm use to functionality similar to this, that just works. For 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 I think the issue lies somewhere in the lookup rules of an actual C++ function, as this example only uses types. Thoughts?

Aucun commentaire:

Enregistrer un commentaire