有关的:
考虑这对可变参数模板:
template<typename Dummy>
bool All(Param& c) {
return true;
}
template<typename Dummy, Func* f, Func* ...rest>
bool All(Param& c) {
return f(c) && All<Dummy, rest...>(c);
}
这可以工作并编译。但是,没有第一个模板参数怎么写呢?
听起来微不足道?嗯,我就是这么想的。:-) 让我们考虑一些想法。
想法1:
template<Func* f, Func* ...rest>
bool All(Param& c) {
return f(c) && All<rest...>(c);
}
template<>
bool All(Param& c) {
return true;
}
行不通...当我尝试这个时,我想到了专业化,但转念一想,这不是它的工作原理。
在原始示例中,我创建了两个不同的重载模板,第一个采用 1 个模板参数,第二个采用 2 个或更多。没有歧义,也没有涉及专业化。我说对了吗?
想法2:
bool All(Param& c) {
return true;
}
template<Func* f, Func* ...rest>
bool All(Param& c) {
return f(c) && All<rest...>(c);
}
显然不会起作用,All<rest...>
因为rest...
为空不会扩展到对非模板函数的调用。
想法3:
让我们重新构建解决方案。
template<Func* f>
bool All(Param& c) {
return f(c);
}
template<Func* f, Func* ...rest>
bool All(Param& c) {
return f(c) && All<rest...>(c);
}
这个是不行的,因为 All(c) 会模棱两可。因此我需要有一个 0-arg 案例和一个 >0-arg 案例......或者 1-arg 案例和一个 >1-arg 案例呢?
想法#3.5:
template<Func* f>
bool All(Param& c) {
return f(c);
}
template<Func* f, Func* f2, Func* ...rest>
bool All(Param& c) {
return f(c) && All<f2, rest...>(c);
}
是的,有效,但包含copypasta(在这种情况下很简单,但可能更大!),因此我会说它并不比我开始的更好。只是另一种解决方法。
想法#4:
让我们尝试#1,但使用类而不是函数。
template<Func* f, Func* ...rest>
struct All {
static bool func(Param& c) {
return f(c) && All<rest...>(c);
}
};
template<>
struct All {
static bool func(Param& c) {
return true;
}
};
这看起来很有希望,因为我可以专攻课程。但是,嘿,它是什么?
抱歉,未实现:无法将“rest ...”扩展为固定长度的参数列表
这不是 GCC 4.4 的事情吗?我在 MinGW GCC 4.6.1 (tdm-1) 上。
无论如何,我应该认为我不能直截了当地做这种基本的事情吗?是否需要使用带有额外虚拟模板参数的解决方法来完成此任务?
或者是否有一个简单、正确的变体来指定零参数的情况,这会起作用吗?