2012-11-06 52 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