Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A C++ monoid trait. Example code shamelessly copied from http://www.scala-lang.org/node/114 . This is just an experiment, how the linked Scala code can be translated into C++.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
using namespace std;
template<class T>
struct Semigroup {
static T add(const T& a, const T& b) {
return a + b;
}
};
template<class T>
struct Monoid : Semigroup<T> {
static T unit();
};
template<>
struct Monoid<int> : Semigroup<int> {
static int unit() { return 0; }
};
template<>
struct Monoid<string> : Semigroup<string> {
static string unit() { return ""; }
};
template<class InputIt,
class T = typename iterator_traits<InputIt>::value_type>
T sum(InputIt first, InputIt last) {
return accumulate(first, last, Monoid<T>::unit(), Monoid<T>::add);
}
int main() {
auto l1 = list<int>{1, 2, 3};
auto l2 = list<string>{"a", "b", "c"};
auto l3 = list<char>{'a', 'b', 'c'};
cout << sum(begin(l1), end(l1)) << endl;
cout << sum(begin(l2), end(l2)) << endl;
//cout << sum(begin(l3), end(l3)) << endl; // does not compile
// undefined reference to `Monoid<char>::unit()'
}
// $ g++ -std=c++11 monoid.cpp
// $ ./a.out
// 6
// abc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.