在回答 CodeReview 上的这个问题时,我正在考虑如何编写模板函数来指示const
包含对象的特性。
具体来说,考虑这个模板化函数
#include <iostream>
#include <numeric>
#include <vector>
template <class It>
typename std::iterator_traits<It>::value_type average(It begin, It end) {
typedef typename std::iterator_traits<It>::value_type real;
real sum = real();
unsigned count = 0;
for ( ; begin != end; ++begin, ++count)
sum += *begin;
return sum/count;
}
int main()
{
std::vector<double> v(1000);
std::iota(v.begin(), v.end(), 42);
double avg = average(v.cbegin(), v.cend());
std::cout << "avg = " << avg << '\n';
}
它需要一个迭代器并根据包含的数字计算平均值,但保证不会通过传递的迭代器修改向量。如何将这一点传达给模板的用户?
请注意,像这样声明它:
template <class It>
typename std::iterator_traits<It>::value_type average(const It begin,
const It end)
不起作用,因为它不是迭代器,而是迭代器指向的东西,即const
. 我必须等待概念标准化吗?
请注意,我不想要求const 迭代器,而是表明它们可以在这里安全地使用。也就是说,我不想限制调用者,而是想传达我的代码正在做出的承诺:“我不会修改你的基础数据。”