Recording

Commit volatile memory to persistent append-only log

0%

两参数版本的 std::accumulate

C++11 的 auto 和 decltype 可以做 “返回值类型推断”。

我写了个两参数版本的 std::accumulate

1
2
3
4
5
6
7
8
9
10
11
#include <numeric>
#include <type_traits>
namespace std {

template <typename InputIt>
auto accumulate(InputIt begin, InputIt end) -> typename std::remove_reference<decltype(*begin)>::type {
typedef typename std::remove_reference<decltype(*begin)>::type ValueType;
return accumulate(begin, end, ValueType());
}

}

配上点测试代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <vector>
#include <utility>
#include <iostream>
#include <iterator>
#include <initializer_list>

template <typename ValueType>
void test(std::vector<ValueType> const& v) {
std::cout << "=========================n";
std::copy(std::begin(v), std::end(v), std::ostream_iterator<ValueType>(std::cout, ", "));
std::cout << "n";

auto sum = std::accumulate(std::begin(v), std::end(v));
std::cout << "sum = " << sum << "n";
std::cout << "=========================nn";
}

template <typename ValueType>
void test(std::initializer_list<ValueType>&& values) {
std::vector<ValueType> v(std::forward<std::initializer_list<ValueType>>(values));
test(v);
}

int
main() {
test<int>(std::vector<int>{});
test<int>({1, 2, 3, 4});
test<int>(std::vector<int>{2,2,3});
test<double>({1.1, 1.2, 1.3});
test<std::string>({"aa", "bb", "cc", "dd"});
std::cout << "cpp : " << __cplusplus << std::endl;
}

EOF