基于c++输入类型参数的返回函数指针



我有一个管理函数指针的类。我想用一个模板或者别的东西通过[]运算符来调用存储在类中的函数。例如,我可以做functions[malloc](0x123),它通过指向类中存储的malloc函数的指针调用malloc。这是我的文件:

#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;
}
};

我试图让模板根据函数的参数扩展/改变返回类型,但我不太确定如何去让它工作。省略了初始化私有字段值的构造函数;它所做的就是获取函数的地址,然后将它们分配给字段。我正在尝试使用c++ 20来做这件事。

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