有时候我们指定一系列区间, 然后由给定值来判定在某个区间之内。初学c语言必定会遇到这样一个问题: 给定学生成绩,来判定是否在A,B,C,D所属之区间内。只不过我们现在研究的是编译期之此等动作。
从底层基本组件实现起, 一个区间实现:
-
-
// 常量区间
-
template <int N1, int N2>
-
struct Rect
-
{
-
enum { Begin = N1 };
-
enum { End = N2 };
-
};
-
为实现区间之判断功能,作为一个动作构件:
-
-
// 检测 一个值是否在某个区间
-
template <int N, class RectType>
-
struct InRect
-
{
-
enum { Value = ( N >= RectType::Begin && N < RectType::End ) };
-
};
为实现区间之任意个数,选用Loki之TypeList辅佐之:
-
-
// 检测 常量区间
-
template <int N, class TList, template <int, class> class InRect>
-
struct CheckRect {};
-
-
template <int N, class Head, class Tail,
-
template <int, class> class InPolicy>
-
struct CheckRect <N, TypeList <Head, Tail>, InPolicy>
-
{
-
typedef typename SelectType < InPolicy<N, Head>::Value,
-
Head,
-
typename CheckRect <N, Tail, InPolicy> ::Result
-
> ::Result
-
Result;
-
};
-
-
template <int N, template <int, class> class InPolicy>
-
struct CheckRect <N, NullType, InPolicy>
-
{
-
typedef EmptyType Result;
-
};
至此,工作已就,测试代码如下:
-
-
#define MakeRect( a, b ) Rect <a, b>
-
-
int main()
-
{
-
typedef CheckRect < 12, TYPELIST_2( MakeRect(1,4), MakeRect(5,19) ), InRect> ::Result My12Rect;
-
-
cout << My12Rect ::Begin << endl;
-
cout << My12Rect ::End << endl;
-
return 0;
-
}
测试代码中,定义了宏 MakeRect 是因C++编译器的宏只认识逗号 (‘,’),比如 TYPELIST_1( Rect <1,2> ) ,编译器的处理是认为TYPELIST_1的参数是 Rect <1 和 2>这两个,因此可能会提示参数过多的警告。
上述只是一初步设想的粗糙版本,尚有多处改进:
1. Default 之接口一致性
2. 更优雅的适应或构造 类 switch case 的语法结构中。
3. 扩展性。如可以自由的后续添加分派动作。
由于上述缺点,尚未能应用于应用中,日后改进。
2022年9月29日 13:32
Mathematics helps us understand the world and provides an effective way of building mental discipline. Math encourages logical reasoning, critical thinking, creative thinking, abstract or spatial thinking, problem-solving ability, and even effective communication. NCERT has introduced the solved question bank with sample paper suggestions for all topics of maths along with solutions. problem-solving ability, NCERT Mathematics Sample Paper Class 9 and even effective communication. NCERT has introduced the solved question bank with sample paper suggestions for all topics of maths along with solutions.