【发布时间】:2012-09-17 04:47:16
【问题描述】:
我自己从未使用过可变参数模板,但我想我现在可能需要它们。假设我有一堂课
class A {
int Kern;
template<int> void func_a(int, double) const;
template<int> void func_b(double, double, char) const;
template<int> unsigned func_c(float, std::vector<int> const&) const;
public
/* ... */
void FuncA(int, double) const;
void FuncB(double, double, char) const;
unsigned FuncC(float, std::vector<int> const&) const;
};
其中A::FuncA()等的定义都是形式
void A::FuncA(int i, double x) const
{
switch(Kern) {
case 1: return func_a<1>(i,x);
case 2: return func_a<2>(i,x);
case 3: return func_a<3>(i,x);
/* ... */
}
}
我目前使用 C 宏实现此开关
#define SwitchKernMacro(KERN,FUNC) \
switch(KERN) { \
case 1: FUNC(1); \
case 2: FUNC(2); \
case 3: FUNC(3); \
/* ... */ \
}
这样
void A::FuncA(int i, double x) const
{
#define FuncK(KERN) return func_a<KERN>(i,x);
SwitchKernMacro(Kern,FuncK);
#undef FuncK
}
我喜欢避免使用这个 C 宏来支持可变参数模板解决方案,这样我的函数的实现就变得简单(或类似)
void A::FuncA(int i, double x) const
{ return SwitchKern(Kern,func_a,i,x); }
void A::FuncB(double a, double b, char c) const
{ return SwitchKern(Kern,func_b,a,b,c); }
unsigned A::FuncC(float f, std::vector<int> const&v) const
{ return SwitchKern(Kern,func_c,f,v); }
模板SwitchKern应该是什么样子的?
编辑
对于 C++ 模板以及何时可以使用它们似乎有些混乱。假设,我只有以下非常简单的功能
class A {
int Kern;
template int> void simple() const;
public:
void Simple() const
{
switch(K) {
case 1: return simple<1>();
case 2: return simple<2>();
case 3: return simple<3>();
default: return simple<0>();
}
}
/* ... */
};
那我也可以通过A::Simple()实现
class A {
/* ... */
template<int> friend struct simple_aux;
};
template<class T, template<int> class SimpleAux>
void Switch(int K, const T* a) {
switch(K) {
case 1: return SimpleAux<1>(a)();
case 2: return SimpleAux<2>(a)();
case 3: return SimpleAux<3>(a)();
default: return SimpleAux<0>(a)();
}
}
template<int k> struct simple_aux
{
const A*const a;
explicit simple_aux(const A*a__) : a(a__) {}
void operator()() { return a->simple<k>(); }
};
void A::Simple() const
{ Switch<A,simple_aux>(K,this); }
但是,此解决方案不允许返回类型不同于void 以及函数A::Simple()(传递给A::simple<>())的任意参数。我的问题是如何使用可变参数模板添加这些功能
【问题讨论】:
-
Func1的第一个参数是在编译时还是运行时确定的? -
那你就不能使用模板了。
-
如果 nothing 是在编译时确定的,则无法通过模板获得它。模板是一种编译时机制。
-
@SethCarnegie 如果您查看代码,您会看到函数参数 types (及其编号)在编译时像往常一样已知,但它们的 价值观.
-
我回复了您的评论,显然您已将其删除。
标签: c++ c++11 variadic-templates