Does function pointers work while I am overloading the functions?

91 views Asked by At

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.

1

There are 1 answers

1
TartanLlama On BEST ANSWER

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);
}