[编辑] 从头开始重写。这样的事情应该是可能的,但是我没有对允许可变参数模板函数不是终点的编译器的访问权,因为这不再需要。如果您不传递至少一个参数,这确实会失败,但我不认为这是一个问题。
template<typename...BL>
struct Recast {
template <typename B, typename ...BR>
struct Inner {
template <typename A, typename ...AR>
static void cast_all(void(*fun)(BL...,B,BR...), BL... al, A a, AR... ar) {
Recast<BL..., B>::template Inner<BR...>::cast_all<AR...>(fun, al..., dynamic_cast<B>(a), ar..);
}
};
template <typename B>
struct Inner<B> {
template <typename A>
static void cast_all(void(*fun)(BL...,B), BL... al, A a) {
fun(al..., dynamic_cast<B>(a));
}
};
};
template <typename ...BR> //note I switched these
struct CastAll{
template <typename ...AR> //note I switched these
static void cast_all(void(*fun)(BR...), AR...ar){
Recast<>::template Inner<BR...>::cast_all(fun, ar...);
}
};
struct A{};
struct B : public A{};
void foo(B *b1, B *b2){
//... does something with b1 and b2
}
int main(){
A *a1 = new B();
A *a2 = new B();
CastAll<B*, B*>::cast_all(foo, a1, a2);
}
我承认仍然存在 ideone.com 报告的我无法弄清楚的错误
prog.cpp: 在静态成员函数'static void Recast::Inner::cast_all(void (*)(BL ..., B, BR ...), BL ..., A, AR ...)' :
prog.cpp:7:39: 错误: '...' 标记前的预期主表达式
prog.cpp:7:39: 错误: 预期';' 在 '...' 标记之前