无法推断可变参数模板参数?

时间:2012-11-06 22:13:26

标签: c++ templates c++11 function-pointers variadic-templates

解释以下测试用例无法编译的根本原因是什么:

#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;
    }
}

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

1 个答案:

答案 0 :(得分:2)

第一个问题是,编译器错误说明:

  

参数包必须位于参数列表的末尾。

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

另外,我不相信编译器会推断使用模板模板的模板函数的类型,因此您必须明确指定模板:

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

Ideone of your snipped with proposed modifications