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.
CodePudding user response:
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);
}