问题描述
我想使用可变参数模板来帮助解决使用va-args的问题。基本上,我想调用一个单数函数,将一个命令与一个变量参数列表一起传递给函数,然后将参数分配给另一个函数。
我已经使用try和true(但不是类型安全)va_list实现了这个。这是我使用可变参数模板进行的尝试。下面的例子没有编译,因为你会很快发现原因...
I would like to use variadic templates to help solve an issue using va-args. Basically, I want to call a singular function, pass into the function a "command" along with a variable list of arguments, then dispatch the arguments to another function.
I've implemented this using tried and true (but not type safe) va_list. Here's an attempt I made at doing this using variadic templates. The example doesn't compile below as you will quickly find out why...
#include <iostream>
using namespace std;
typedef enum cmd_t
{
CMD_ZERO,
CMD_ONE,
CMD_TWO,
} COMMANDS;
int cmd0(double a, double b, double c)
{
cout << "cmd0 " << a << ", " << b << ", " << c << endl;
return 0;
}
int cmd1(int a, int b, int c)
{
cout << "cmd1 " << a << ", " << b << ", " << c << endl;
return 1;
}
template<typename... args>
int DispatchCommand(COMMANDS cmd, Args... args)
{
int stat = 0;
switch (cmd)
{
case CMD_ZERO:
cmd0(args...);
break;
case CMD_ONE:
cmd1(args...);
break;
default:
stat = -1;
break;
}
return stat;
}
int main()
{
int stat;
stat = DispatchCommand(CMD_ZERO, 1, 3.141, 4);
stat = DispatchCommand(CMD_ONE, 5, 6, 7);
stat = DispatchCommand(CMD_TWO, 5, 6, 7, 8, 9);
system("pause");
return 0;
}
有没有人知道如何修改此函数以正确使用可变参数模板?
Does anyone have an idea on how I can modify this function to use variadic templates correctly?
推荐答案
template<int>
class Dispatcher
{
public:
template <typename... Args>
static int exec(Args... args) {
return -1;
}
};
template<>
class Dispatcher<CMD_ZERO>
{
public:
template <typename... Args>
static int exec(Args... args) {
cmd0(args...);
return 0;
}
};
template<>
class Dispatcher<CMD_ONE>
{
public:
template <typename... Args>
static int exec(Args... args) {
cmd1(args...);
return 0;
}
};
template <int _Cmd, typename... Args >
int DispatchCommand(Args... args)
{
return Dispatcher<_Cmd>::exec(args...);
}
int main()
{
int stat;
stat = DispatchCommand<CMD_ZERO>(1, 3.141, 4);
stat = DispatchCommand<CMD_ONE>(5, 6, 7);
stat = DispatchCommand<CMD_TWO>(5, 6, 7, 8, 9);
system("pause");
return 0;
}
当然,这只适用于DispatchCommand的模板参数是编译时常量.....我希望这有一些帮助吗?
Of course, this only works if the template parameters to DispatchCommand are compile time constants..... I hope this is of some help ?
这篇关于使用可变参数模板创建一个简单的调度程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!