2
#include <stdio.h>
#include <functional>

int foo(int x)
{
    return x;
}

int foo(int a, int b)
{
    return a + b;
}

int main()
{
    std::function<int(int)> guiFunc2 = foo;      //error : no suitable constructor exists to convert from "<unknown-type>" to "std::function<int(int)>"
    std::function<int(int, int)> guiFunc1 = foo; //error : no suitable constructor exists to convert from "<unknown-type>" to "std::function<int(int, int)>"

    return 0;
}

I want to make two function pointers to functions with same name but this code does not work.

It's easy to just change the functions name but I would like to know if it's possible to make funtion pointers with same name.

Thanks.

5
  • 2
    en.cppreference.com/w/cpp/language/overloaded_address Commented Mar 4, 2020 at 11:01
  • 1
    Hmm... why did @rafix07 remove the answer? It looked good, didn't it? Commented Mar 4, 2020 at 11:05
  • 1
    I fixed what I think was a typo, if it wasnt sorry. Commented Mar 4, 2020 at 11:09
  • 1
    Please, note the difference between function overloading and overriding. Overriding is related to virtual functions and inheritance. Commented Mar 4, 2020 at 11:12
  • @DanielLangr Good catch. Edited since the code shows overloading. Commented Mar 4, 2020 at 11:14

2 Answers 2

4

Cast the address to correct type before assignment:

std::function<int(int)> guiFunc2 = static_cast<int(*)(int)>(foo);
std::function<int(int, int)> guiFunc1 = static_cast<int(*)(int, int)>(foo);
Sign up to request clarification or add additional context in comments.

3 Comments

May I ask one more thing? What I've learnt is that 'c++ compiler discriminates one overrided function from another by check its 'arguments' and 'function name'' and the functions in my code have different arguments. Why must I type-cast them?
@GamerCoder You are not calling the function, so there are no arguments from which to deduct the type.
@GamerCoder int(*guiFunc2)(int) = foo; int(*guiFunc1)(int,int) = foo; works though if you don't like the casting.
0

For me this is more handy:

    auto a = [](int x) { return foo(x); };
    auto b = [](int a, int b) { return foo(a, b); };

https://wandbox.org/permlink/yjc5EiEY97wgfN9b

Result should be same as other answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.