7

this question seems a little bit silly to me but I can't find any similar question so sorry if it's trivial

let's say we have a struct:

struct C {
  static void f(int i) { std::cerr <<  (i + 15) << "\n"; }
  static void f(std::string s) { std::cerr <<  (s + "15") << "\n"; }
};

now somewhere else:

std::function<void(int)> f1 = C::f; // this does not compile
void (*f2)(std::string s) = C::f;   // this compiles just fine

the error I'm getting is

error: conversion from ‘’ to non-scalar type ‘std::function’ requested

is there any way to use std::function in such context? what am I missing?

thanks

user2717954
  • 1,822
  • 2
  • 17
  • 28

1 Answers1

8
std::function<void(int)> f1 = C::f; // this does not compile

C::f is an overload set which does not have an address. You can create a wrapper FunctionObject around it:

std::function<void(int)> f1 = [](int x){ return C::f(x); };

void (*f2)(std::string s) = C::f;   // this compiles just fine

This line compiles because you're "selecting" the std::string overload of the C::f overload set by explicitly assigning it to a void(*)(std::string) pointer.

You can do the same thing for f1:

 std::function<void(int)> f1 = static_cast<void(*)(int)>(&C::f);
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • I sort of understood that (well not really, maybe *guessed* that it is the cause). but why can't the compiler infer the selected overload when using std::function? – user2717954 Jan 15 '18 at 12:01
  • @user2717954: https://stackoverflow.com/questions/30393285/stdfunction-fails-to-distinguish-overloaded-functions , https://stackoverflow.com/questions/31172921/different-overloads-with-stdfunction-parameters-is-ambiguous-with-bind-someti – Vittorio Romeo Jan 15 '18 at 12:08