11

I have an overloaded function which I want to pass along wrapped in a std::function. GCC4.6 does not find a "matching function". While I did find some questions here the answers are not as clear as I would like them. Could someone tell me why the following code can not deduct the correct overload and how to (elegantly) work around it?

int test(const std::string&) {
    return 0;
}

int test(const std::string*) {
    return 0;
}

int main() {
    std::function<int(const std::string&)> func = test;
    return func();
}
abergmeier
  • 13,224
  • 13
  • 64
  • 120

1 Answers1

21

That is ambiguous situation.

To disambiguate it, use explicit cast as:

typedef int (*funtype)(const std::string&);

std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!

Now the compiler would be able to disambiguate the situation, based on the type in the cast.

Or, you can do this:

typedef int (*funtype)(const std::string&);

funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!

So why std::function<int(const std::string&)> does not work the way funtype fun = test works above?

Well the answer is, because std::function can be initialized with any object, as its constructor is templatized which is independent of the template argument you passed to std::function.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    Please use `static_cast` in place of old style cast. – Anonymous Apr 11 '12 at 17:47
  • @Anonymous: Yes. But I wanted to make it short. Anyway, I edited it to make it look like C++-ish! – Nawaz Apr 11 '12 at 17:48
  • How ironic - you have to use function pointers to get a std::function, which were introduced to get away from function pointers :) thx – abergmeier Apr 11 '12 at 17:49
  • 1
    @LCIDFire: `std::function` was not introduced to get rid of function pointers, but to provide a more general solution. You can use `std::function` and use any of function pointers, lambdas, functors (including binders)... – David Rodríguez - dribeas Apr 11 '12 at 19:17