简体   繁体   中英

How can I point a function with function overload?

#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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM