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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With