使用可变参数模板构建函数参数 [英] Build function parameters with variadic templates

查看:55
本文介绍了使用可变参数模板构建函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个示例代码,可以完成3参数函数的工作:

I have this sample code, which do what I need for a 3-parameter function :

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 模板仅用于显示呼叫).

(the GETPARAM templates are there just to show the call).

我尝试使用可变参数模板将其泛化为带有任意数量参数的函数,但均未成功.有可能吗?

I tried to generalize it with a variadic template for functions with any number of arguments with no success. Is it possible ?

模板应可用于具有任何返回类型和任意数量参数的任何 T(* fn)(P1,P2,...),并在运行时调用 GETPARAM< Pn>().

The template shall be useable for any T (*fn)(P1, P2, ...) with any return type and any number of parameters, building the parameters on the fly calling the GETPARAM<Pn>() for each of them.

需要为脚本语言创建绑定系统,从堆栈中获取参数并在完成后调用C ++函数.

It's needed to create a binding system for a scripting language, fetching parameters from a stack and calling a C++ function when done.

推荐答案

我尝试使用可变参数模板将其泛化为带有任意数量参数的函数,但均未成功.有可能吗?

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

以下是一个完整的工作示例

The following is a full working example

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

这篇关于使用可变参数模板构建函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆