Maksim Melnik
Maksim Melnik

Reputation: 565

C++ put function pointer into a map in one line

In my project i have following functions:

static void test0(void)
{
    printf("%s [%d]\n", __func__, __LINE__);
}

static void test0(int a)
{
    printf("%s [%d] %d\n", __func__, __LINE__, a);
}


static std::map<std::string, void*> getAddressMap()
{
    std::map<std::string, void*> addressmap;

    void (*select1)(void) = test0;  // will match void(void)
    addressmap["test0"]=reinterpret_cast<void *>(select1);

    void (*select2)(int) = test0;   // will match void(int)
    addressmap["test0"]=reinterpret_cast<void *>(select2);
    return addressmap;
}

At this point you can see that in order to store each pointer in the map I need to define a special pointer and only then i can store it in the map...

Since all of these methods and stubs i am generating from a template, it would be more practical to do it using just one line. So, my question is, is there a way to do it in just one line ?

Upvotes: 0

Views: 87

Answers (1)

Robert
Robert

Reputation: 1343

Casting the function pointer (before casting to void*) should work just fine...

addressmap["test0"] = reinterpret_cast<void *>(static_cast<void(*)(void)>(test0));
addressmap["test0"] = reinterpret_cast<void *>(static_cast<void(*)(int)>(test0));

Upvotes: 1

Related Questions