我正在尝试为不同的函数实现一个容器类,我可以在其中保存函数指针并使用它来稍后调用这些函数.我会尝试更准确地描述我的问题.
例如,我有两种不同的测试功能:
int func1(int a, int b) {
printf("func1 works! %i %i\n", a, b);
return 0;
}
void func2(double a, double b) {
printf("func2 works! %.2lf %.2lf\n", a, b);
}
Run Code Online (Sandbox Code Playgroud)
我还有一系列变体,它们包含函数参数:
std::vector<boost::variant<int, double>> args = {2.2, 3.3};
Run Code Online (Sandbox Code Playgroud)
我已经决定使用从某个基类派生的我自己的仿函数类(我考虑过使用虚方法):
class BaseFunc {
public:
BaseFunc() {}
~BaseFunc() {}
};
template <typename T>
class Func;
template <typename R, typename... Tn>
class Func<R(Tn...)> : public BaseFunc {
typedef R(*fptr_t)(Tn...);
fptr_t fptr;
public:
Func() : fptr(nullptr) {}
Func(fptr_t f) : fptr(f) {}
R operator()(Tn... args) …Run Code Online (Sandbox Code Playgroud)