我想创造一个简单的辅助算法,将填充的容器,如std::vector<T>
,具有几何级数(第一项是a
,并且n
个术语由下式给出a * pow(r, n-1)
,其中r
是给定的比例);我创建了下面的代码:使用模板的模板时失败模板参数推导参数
#include<vector>
#include<algorithm>
#include<iostream>
template<template <typename> class Container, typename T>
void progression(Container<T>& container, T a, T ratio, size_t N) {
if(N > 0) {
T factor = T(1);
for(size_t k=0; k<N; k++) {
container.push_back(a * factor);
factor *= ratio;
}
}
}
int main() {
std::vector<double> r;
progression(r, 10.0, 0.8, static_cast<size_t>(10));
for(auto item : r) {
std::cout<<item<<std::endl;
}
return 0;
}
这在尝试编译产生了以下错误:
$ g++ geometric.cpp -std=c++11 # GCC 4.7.2 on OS X 10.7.4
geometric.cpp: In function ‘int main()’:
geometric.cpp:18:52: error: no matching function for call to ‘progression(std::vector<double>&, double, double, size_t)’
geometric.cpp:18:52: note: candidate is:
geometric.cpp:6:6: note: template<template<class> class Container, class T> void progression(Container<T>&, T, T, size_t)
geometric.cpp:6:6: note: template argument deduction/substitution failed:
geometric.cpp:18:52: error: wrong number of template arguments (2, should be 1)
geometric.cpp:5:36: error: provided for ‘template<class> class Container’
锵的错误消息是更加微妙:
$ clang++ geometric.cpp -std=c++11 # clang 3.2 on OS X 10.7.4
geometric.cpp:18:3: error: no matching function for call to 'progression'
progression(r, 10, 0.8, 10);
^~~~~~~~~~~
geometric.cpp:6:6: note: candidate template ignored: failed template argument deduction
void progression(Container<T>& container, T a, T ratio, size_t N) {
^
1 error generated.
我本来期望的是使用模板模板参数我不仅能够推导出容器,还能推导容器的value_type
(在这种情况下为T
)。
所以,问题是:如何创建一个泛型函数,它将能够推导出容器类型和值类型?
我相信我错过了一些明显的东西 - 我感谢您的耐心和帮助。
编辑(答案)
下面的代码的行为与预期:
#include<vector>
#include<algorithm>
#include<iostream>
template<template <typename...> class Container, typename T, typename... Args>
void progression(Container<Args...>& container, T a, T ratio, size_t N) {
if(N > 0) {
T factor = T(1);
for(size_t k=0; k<N; k++) {
container.push_back(a * factor);
factor *= ratio;
}
}
}
int main() {
std::vector<double> r;
progression(r, 10.0, 0.8, 10);
for(auto item : r) {
std::cout<<item<<std::endl;
}
return 0;
}
输出:
10
8
6.4
5.12
4.096
3.2768
2.62144
2.09715
1.67772
1.34218
谢谢!这解决了这个问题。 – Escualo
我其实有这个答案的改进版本,但我的网络连接断开,我无法从我的手机进行编辑(它只是一团糟)。 –
@阿列塔:很高兴帮助! –