Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return function pointer based on input type parameter C++

I have a class for managing function pointers. I want to use a template or something to call the function stored in the class via the [] operator. For example, I can do functions[malloc](0x123), which calls malloc via a pointer to the malloc function stored in the class. This is what I have:

#include <cstdlib>
#include <iostream>
    
class DelayedFunctions
{
    decltype(&malloc) malloc;
    decltype(&free) free;
public:
    template <typename T>
    constexpr T operator[](T)
    {
        if (std::is_same_v<T, decltype(&malloc)>)
            return malloc;
        if (std::is_same_v<T, decltype(&free)>)
            return free;
        return 0;
    }
};

I’m trying to get the template to expand/change the return type based on the function’s arguments, but I’m not so sure how to go about getting it to work. The constructor which initializes the values of the private fields is omitted; all it does is get the addresses of the functions and then assign them to the fields. I’m trying to use C++20 to do this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Works well with if constexpr

#include <cstdlib>
#include <type_traits>

class DelayedFunctions
{
    decltype(&std::malloc) malloc = std::malloc;
    decltype(&std::free) free = std::free;
public:
    template <typename T>
    constexpr T operator[](T)
    {
        if constexpr (std::is_same_v<T, decltype(&std::malloc)>)
            return malloc;
        if constexpr (std::is_same_v<T, decltype(&std::free)>)
            return free;
        return {};
    }
};

DelayedFunctions functions;

int main() {
    auto *p = functions[malloc](123);
    functions[free](p);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading