Skip to content

Instantly share code, notes, and snippets.

@fthomas
Created December 15, 2012 10:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fthomas/4292455 to your computer and use it in GitHub Desktop.
Save fthomas/4292455 to your computer and use it in GitHub Desktop.
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