简体   繁体   English

使用C ++的高级类型

[英]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++... 这个问题适用于了解Haskell(或任何其他支持高级类型的函数语言)和C ++的人...

Is it possible to model higher kinded types using C++ templates? 是否可以使用C ++模板对更高级的kinded类型进行建模? If yes, then how? 如果是,那怎么样?

EDIT : 编辑:

From this presentation by Tony Morris: 演示文稿由托尼·莫里斯:

Higher-order Polymorphism : 高阶多态性:

  • Languages such as Java and C# have first-order polymorphism because they allow us to abstract on types. Java和C#等语言具有一阶多态性,因为它们允许我们对类型进行抽象。 eg List<A> can have a reverse function that works on any element type (the A ). 例如, List<A>可以具有适用于任何元素类型( A )的reverse函数。

  • More practical programming languages and type systems allow us to abstract on type constructors as well. 更实用的编程语言和类型系统允许我们在类型构造函数上进行抽象。

  • This feature is called higher-order (or higher-kinded) polymorphism. 此功能称为高阶(或更高阶)多态。

Example : 示例:

Pseudo-Java with an invented notation for higher-order polymorphism 伪Java,发明了高阶多态性的符号

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);
}

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 action;
        else
            return function(action.value);
    }
};

Isn't usually a normal template already a higher-kinded type? 通常不是普通模板已经是更高级的类型? For example std::vector takes a type parameter to create an actual type like std::vector<int> , so it has kind * -> * . 例如, std::vector接受一个类型参数来创建一个像std::vector<int>这样的实际类型,所以它有类型* -> *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM