我有这个示例代码,它可以满足我对 3 参数函数的需求:
template<typename T>T GETPARAM(void) { return T(); }
template<>int GETPARAM(void) { return 123; }
template<>double GETPARAM(void) { return 1.2345; }
template<>const char *GETPARAM(void) { return "hello"; }
template<typename P1, typename P2, typename P3, typename RES> RES BuildArgs3(RES(*fn)(P1, P2, P3)) {
P1 p1 = GETPARAM<P1>();
P2 p2 = GETPARAM<P2>();
P3 p3 = GETPARAM<P3>();
return fn(p1, p2, p3);
}
int print3(int a, double b, const char *c)
{
Cout() << "Print3:" << a << ", " << b << ", " << c << "\n";
return 1;
}
main() {
BuildArgs3(print3);
}
(GETPARAM
模板只是为了显示调用)。
我尝试使用可变参数模板将其概括为具有任意数量参数的函数,但没有成功。可能吗?
模板应可用于任何 T (*fn)(P1, P2, ...)
具有任何返回类型和任意数量的参数,动态构建参数调用 GETPARAM<Pn>()
对于他们每个人。
需要为脚本语言创建绑定(bind)系统,从堆栈中获取参数并在完成时调用 C++ 函数。
最佳答案
I tried to generalize it with a variadic template for functions with any number of arguments with no success. Is it possible ?
是的;而且很简单
template <typename R, typename ... Args>
R BuildArgsN (R(*fn)(Args...))
{ return fn(GETPARAM<Args>()...); }
下面是一个完整的工作示例
#include <iostream>
template<typename T>T GETPARAM(void) { return T(); }
template<>int GETPARAM(void) { return 123; }
template<>double GETPARAM(void) { return 1.2345; }
template<>const char *GETPARAM(void) { return "hello"; }
template <typename R, typename ... Args>
R BuildArgsN (R(*fn)(Args...))
{ return fn(GETPARAM<Args>()...); }
int print3 (int a, double b, char const * c)
{
std::cout << "Print3:" << a << ", " << b << ", " << c << "\n";
return 1;
}
int main ()
{
BuildArgsN(print3);
}
关于c++ - 使用可变参数模板构建函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47207621/