我正在嘗試編寫用於計算兩個向量的標量積的函數。 這是代碼,它的工作原理。具有多種類型的遞歸模板函數
template <int N>
int scalar_product (std::vector<int>::iterator a,
std::vector<int>::iterator b) {
return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1);
}
template <>
int scalar_product<0>(std::vector<int>::iterator a,
std::vector<int>::iterator b) {
return 0;
}
但現在的問題是 - 我要取代這個迭代器與模板類型,這樣的功能簽名看起來水木清華這樣
template <typename Iterator ,int N>
int scalar_product (Iterator a, Iterator b) {
return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1);
}
template <typename Iterator>
int scalar_product<0>(Iterator a,
Iterator b) {
return 0;
}
但是,這並不工作 - 我得到編譯錯誤C2768:非法使用顯式模板參數。這似乎很愚蠢,但我無法找出我應該改變什麼來避免這個錯誤。
看到這個:http://stackoverflow.com/questions/3716799/partial-specialization-函數功能模板 – Nim
爲什麼不使用['std :: inner_product'](http://en.cppreference.com/w/cpp/algorithm/inner_product)?內聯循環對你如此重要? – gwiazdorrr
@Nim感謝您的鏈接 - 它幫助。 – htzfun