3

I am just practicing function pointers.

#include <iostream>
#include <functional>

void print(){
    std::cout << "Printing VOID...\n";
}
void printI(int a){
    std::cout << "Printing INTEGER..."<<a<<"\n";
}
int main(){
    std::function<void(void)> p;
    std::function<void(int)> pi;
    p = print;
    pi = printI;
    p();
    pi(10);
}

Now this code works fine and gives me the output.. But what i want to do is to overload the print function like below.

#include <iostream>
#include <functional>

void print(){
    std::cout << "Printing VOID...\n";
}
void print(int a){
    std::cout << "Printing INTEGER..."<<a<<"\n";
}
int main(){
    std::function<void(void)> p;
    std::function<void(int)> pi;
    p = print;
    pi = print;
    p();
    pi(10);
}

But This code isn't working. It says unresolved address for print. Is there any way I can achieve both functionality? I mean Function pointer and Overloading.

01000001
  • 833
  • 3
  • 8
  • 21
  • possible duplicate of [Wrap overloaded function via std::function](http://stackoverflow.com/questions/10111042/wrap-overloaded-function-via-stdfunction) – NathanOliver Jun 09 '15 at 13:48

1 Answers1

4

You could either try the standard static_cast method, or you could write a function template helper to do the type cohersion for you:

template <typename Ret, typename... Args>
auto assign_fn (std::function<Ret(Args...)> &f, Ret (*fp) (Args...))
{
    f = fp;
}

This is then used like so:

int main(){
    std::function<void(void)> p;
    std::function<void(int)> pi;
    assign_fn(p,print);
    assign_fn(pi,print);
    p();
    pi(10);
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • Is there any way to make it working for convertible functions, e.g. call assign_fn on std::function and void(float)? – Ivanq May 17 '20 at 15:58