2012-11-06 99 views
1

是什么解释,下面的测试案例编译失败的根本原因:推导可变参数模板失败?

#include <iostream> 
#include <vector> 
#include <numeric> 
#include <algorithm> 

template<typename Type, typename... Args> 
void apply(std::vector<Type> &v, Args... args, void(*algo)(Type*, Type*, Args...)) 
{ 
    algo(&*v.begin(), &*v.end(), args...); 
} 

int main() 
{ 
    std::vector<int> v(10, 50); 
    apply(v, 3, std::iota); 
    for (unsigned int i = 0; i < v.size(); ++i) { 
     std::cout<<v[i]<<std::endl; 
    } 
} 

是否有函数原型解决方法?

回答

2

第一个问题是,因为编译器错误状态:

参数包必须出现在参数列表的末尾。

换句话说,您必须声明您的函数,Args ... args是列表中的最后一个参数。

而且,我不相信,编译器会推断,使用模板模板您使用它们的方式模板函数的类型,所以你必须明确指定模板:

apply<int, int>(v, std::iota, 3); // or something 

Ideone of your snipped with proposed modifications

+1

'apply (v,std :: iota,3);'[也很好](http://liveworkspace.org/code/6809848b76a05fc6c5f947d36c8063b7) - 不需要手动指定'Args ...' 。 (并且此处没有模板模板参数。) – ildjarn

+0

模板模板是错误的词,但我想不出正确的模板模板参数。 – Wug