lundi 23 avril 2018

How C++ compiler locate overloaded function

I found one confusing question that why C++ compiler can not locate an overloaded function like this. I am curious about the underlying mechanism.

BTW, I found a solution using a 'static_cast' or wrap the desired a function with a lambda. Is there other solution?

#include <functional>
#include <iostream>
using std::cout;

namespace ns {
void f(int a) {
  cout << a;
}

/*
 * won't compile with a overloaded function.
 * a.cc: In constructor ‘wrapper::wrapper()’:
a.cc:17:28: error: no matching function for call to ‘wrapper::wrapper(<unresolved overloaded function type>)’
   wrapper() : wrapper(ns::f) {
                            ^
a.cc:19:3: note: candidate: wrapper::wrapper(const std::function<void(int)>&)
   wrapper(const std::function<void(int)>& func) {
   ^~~~~~~
a.cc:19:3: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘const std::function<void(int)>&’
a.cc:17:3: note: candidate: wrapper::wrapper()
   wrapper() : wrapper(ns::f) {
   ^~~~~~~
a.cc:17:3: note:   candidate expects 0 arguments, 1 provided
a.cc:15:7: note: candidate: constexpr wrapper::wrapper(const wrapper&)
 class wrapper {
       ^~~~~~~
a.cc:15:7: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘const wrapper&’
a.cc:15:7: note: candidate: constexpr wrapper::wrapper(wrapper&&)
a.cc:15:7: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘wrapper&&’
*/
void f(char a[]) {
}


}

class wrapper {
 public:
  wrapper() : wrapper(static_cast<void(*)(int)>(&ns::f)) {
  }
  wrapper(const std::function<void(int)>& func) {
    func(32);
  }
};

int main() {
  wrapper w;
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire