zoukankan      html  css  js  c++  java
  • 模板元编程

      分三个部分,只有一个数的情况,比较两个数的情况,其它情况。其它情况为入口,模板递归到两个的情况,比较出值之后一层一层返回,然后计算出结果。

    #include <iostream>
    
    using std::cout;
    
    template<int First, int ...Others>
    struct Min {
    	enum { value = First > Min<Others...>::value ? Min<Others...>::value : First };
    };
    
    template<int LeftVal, int RightVal>
    struct Min<LeftVal, RightVal> {
    	enum { value = LeftVal < RightVal ? LeftVal : RightVal };
    };
    
    template<int Last>
    struct Min<Last> {
    	enum { value = Last };
    };
    
    template<int First, int ...Others>
    struct Max {
    	enum { value = First < Max<Others...>::value ? Max<Others...>::value : First };
    };
    
    template<int LeftVal, int RightVal>
    struct Max<LeftVal, RightVal> {
    	enum { value = LeftVal > RightVal ? LeftVal : RightVal };
    };
    
    template<int Last>
    struct Max<Last> {
    	enum { value = Last };
    };
    
    int main()
    {
    	cout << Min<11, 5, 1, -2, 3, 0, -1>::value << '
    ';
    	cout << Max<11, 5, 1, -2, 3, 0, -1>::value << '
    ';
    	return 0;
    }
    

      根据个人理解的话,函数式编程的一个基本概念就是类的映射,这里的类是数学上的概念,和集合有些类似,但概念比集合更广一些。也就是说,在写函数式风格的代码的时候会把重点关注放到「将需求思想转为对一个类到另一个类的一个映射」,比如:

    f :: Bool -> Bool
    f :: Integer -> Integer
    f :: Integer -> Bool
    f :: Integer -> Float
    f :: [] -> []
    f :: (x, y) -> (x, y)
    ...

      所以语句很类似数学语言那样精炼的表达方式,以及有些地方类似 SQL 那样的语法来操纵集合,当然函数式还有其它重要概念,高阶函数(high-order function)(类似 python、java 等的装饰器)、函子(functor)、Monads 等,但自己还写得太少,所以不敢胡乱理解,等再写一段时间吧。

  • 相关阅读:
    《ML模型超参数调节:网格搜索、随机搜索与贝叶斯优化》
    《黎曼几何与流形学习》
    《信息几何优化,随机优化, 与进化策略》
    生产订单加反作废按钮
    生产订单新增按钮没权限
    生产订单备注字段锁定
    审核后提交物料附件
    MRP设置自动执行
    CRM系统数据授权
    复制物料时不复制安全库存
  • 原文地址:https://www.cnblogs.com/darkchii/p/13768604.html
Copyright © 2011-2022 走看看