I’ve had a hypothesis for a while that C++ templates (paired at times with ADL) are an ad-hoc, unsound version of typeclasses. I’ve seen this hold for parser combinators, range base algorithms, and more. I’m also not the first to draw this comparison[1].
Concepts are supposed to bring soundness in through constrained templates. Concepts look awfully a lot like type classes; they export functions and types, and are parameterized, and act as constraints on generic functions and other concepts. I checked the draft specification [2], and it even seems to permit parameterizing concepts on type constructors, just like Haskell! (er, C++ calls them class templates, not type constructors. to-may-to, to-mah-to)
But I worried I may be mistaken about concepts, as I’ve searched through google and literature and have yet to find a single example in literature demonstrating the use of template template concepts.
In case you’re curious what this might look like, here’s an educated guess:
concept Monad<template <> class m> {
template<typename T, typename U>
m<U> mbind(m<T>, function<m<U>(T)>);
template<class T>
m<T> mreturn(T);
};
template <template <typename> class m,
class T,
class U,
class Iter>
requires M<m>
requires InputIterator<Iter, U>
m<T> foldM(Iter begin, Iter end, T i, function<m<T>(T, U)> f)
{
if(begin == end)
return mreturn(i);
else
return mbind(f(i, *begin), [=](T result){
Iter next = begin;
++next;
return foldM(next, end, result, f);
});
}
Have template template concepts been covered thoroughly somewhere, and I’ve just missed it?
- [1] “C++ templates/traits versus Haskell typeclasses” (2005), by Sunil Kothari, Martin Sulzmann.
- [2] “Proposed Wording for Concepts (Revision 5)” (2008).
- [3] “Trip Report: Exit Concepts, Final ISO C++ Draft in ~18 Months” (2009), Herb Sutter.
- [4] “ConceptClang: An Implementation of C++ Concepts in Clang” [pdf]