Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 binding std function to a overloaded static method

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

like image 332
user2717954 Avatar asked Jan 15 '18 11:01

user2717954


Video Answer


1 Answers

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);
like image 178
Vittorio Romeo Avatar answered Sep 30 '22 17:09

Vittorio Romeo