c++templateshaskellhigher-kinded-types

Higher-kinded Types with C++


This question is for the people who know both Haskell (or any other functional language that supports Higher-kinded Types) and C++...

Is it possible to model higher kinded types using C++ templates? If yes, then how?

EDIT :

From this presentation by Tony Morris:

Higher-order Polymorphism :

Example :

Pseudo-Java with an invented notation for higher-order polymorphism

interface Transformer<X, Y> {
  Y transform(X x);
}

interface Monad<M> { // M :: * -> *
  <A> M<A> pure(A a);
  <A, B> M<B> bind(Transformer<A, M<B>> t, M<A> a);
}

Solution

  • Template-template parameters?

    template <template <typename> class m>
    struct Monad {
        template <typename a>
        static m<a> mreturn(const a&);
        
        template <typename a, typename b>
        static m<b> mbind(const m<a>&, m<b>(*)(const a&));
    };
    
    template <typename a>
    struct Maybe {
        bool isNothing;
        a value;
    };
    
    template <>
    struct Monad<Maybe> {
        template <typename a>
        static Maybe<a> mreturn(const a& v) {
            Maybe<a> x;
            x.isNothing = false;
            x.value = v;
            return x;
        }
        
        template <typename a, typename b>
        static Maybe<b> mbind(const Maybe<a>& action, Maybe<b>(*function)(const a&)) {
            if (action.isNothing)
                return Maybe<b>{true, b{}};
            else
                return function(action.value);
        }
    };