模板元编程

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

#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 等,但自己还写得太少,所以不敢胡乱理解,等再写一段时间吧。

原文地址:https://www.cnblogs.com/darkchii/p/13768604.html